换位和排列 - 运行时错误

Transpositions and Permutations - Runtime error

这是我要回答的问题:

找到将序列 MARINE(字母编号为 0..5)转换为序列 AIRMEN 的字母换位序列。转置由整数对表示。例如,对 (0,1) 将 MARINE 转换为 AMRINE。换位是从左到右进行的。你应该通过这样写来定义序列(点应该用数字代替,括号中的每一对指定一个排列,这些排列是按顺序执行的,从左到右):

定义序列():

return [(...,...),..., (...,...)]

当我 运行 程序时,我似乎遇到 运行 时间错误。我无法找到错误所在。如果我能得到一些帮助,那将非常有用。谢谢! :)

这是我的代码:

def sequence(original, target):

    permutation = []

    chars_original = []
    for char in original:
        chars_original.append(char)
    #print('original: ', chars_original)

    chars_target = []
    for char in target:
        chars_target.append(char)
    #print('target: ', chars_target)


    for i in range(0, len(target)):
        if chars_target[i]== chars_original[i]:
            continue
        else:
            temp_list = []
            temp_list.append(i)
            j = chars_original.index(chars_target[i])
            temp_list.append(j)
            temp = chars_original[i]
            chars_original[i] = chars_original[j]
            chars_original[j] = temp
            a = tuple (temp_list)
            permutation.append(a)
            #print(permutation)
            #print(chars_original)

    return permutation

sequence('MARINE', 'AIRMEN')

你能试试这个吗


def sequence(original, target):

    # convert to list so the string becomes mutable
    original = list(original) 
    target = list(target)

    seq = []

    for i in range(len(original)):
        if original[i] != target[i]:
            for j in range(i+1, len(original)):
                if original[j] == target[i]:
                    original[i], original[j] = original[j], original[i] # swap if the same
                    seq.append((i, j))
    return seq

sequence('MARINE', 'AIRMEN')

def sequence(y,z):
  a=list(y)
  b=list(z)
  d=0
  l=[]
  while(d<len(y)):
    if(a[d]==b[d]):
      d=d+1
    else:
      e=a.index(b[d])
      a[e],a[d]=a[d],b[d]
      l=l+[(d,e)]
  return l
    
print(sequence("MARINE","AIRMEN"))