Saitama
Saitama

Reputation: 25

Transpositions and Permutations - Runtime error

This is the question I have to answer:

Find a sequence of transpositions of letters that transform the sequence MARINE (letters are numbered 0..5) to the sequence AIRMEN. Transpositions are represented by pairs of integers. For example, the pair (0,1) transforms MARINE to AMRINE. Transpositions are performed from left to right. You should define the sequence by writing something like this (the dots should be replaced by numbers, each pair in parentheses specifies one permutation, and these permutations are performed sequentially, from left to right):

def sequence():

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

When I run the program i seem to get a runtime error. I'm unable to find where the error is. It would be very useful, if I could get some help. Thanks! :)

This is my code:

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')

Upvotes: 2

Views: 1858

Answers (2)

Shambhav Agrawal
Shambhav Agrawal

Reputation: 151

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"))

Upvotes: 0

dimitris_ps
dimitris_ps

Reputation: 5951

Can you try this


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')

Upvotes: 1

Related Questions