0

A text is divided in groups with seven letters. Each group is scrambled with the key 6015423 (letter with index 0 on index 6, letter with index 1 on index 0, letter with index 2 on index 1...).

Instead of the correct word "serpent" (tried it only with the first seven-letter group, the same problem occurs when %7 is left out) my code yields a false result beginning with index 4: serpsne.

What is the mistake?

list=['e','r','n','t','e','p','s']
clear=[]
for x in list:    
    if list.index(x)%7==0:
        a=list[list.index(x)+6]
    elif list.index(x)%7==1:
        a=list[list.index(x)-1]
    elif list.index(x)%7==2:
        a=list[list.index(x)-1]
    elif list.index(x)%7==3:
        a=list[list.index(x)+2]
    elif list.index(x)%7==4:
        a=x
    elif list.index(x)%7==5:
        a=list[list.index(x)-3]
    else:               
        a=list[list.index(x)-6]
    clear.append(a)
clear=''.join(clear)
print(clear)

(Don´t know why this box inserts two blank lines after for and else, my code has no blank lines.)

num3ri
  • 822
  • 16
  • 20

2 Answers2

1

Not sure why you're doing this much! Try this one below:

lst=['e','r','n','t','e','p','s']
clear=[]
key='6015423'
for x in key:
    clear.append(lst[int(x)])

clear=''.join(clear)
print(clear)
Sandesh34
  • 279
  • 1
  • 2
  • 14
  • Thanks a lot. I used the modulo thing because 'list' , unlike in my example given above, consists of many seven-letter groups, all transposed with the identical key. I'll try to multiply 'key' in your code so that it becomes as long as 'list'. – Tobi Nov 22 '18 at 09:20
0

Because list.index('e') is always 0.

It will find the index of the first occurence of 'e', not the second one and hence it will never execute this:

elif list.index(x)%7==4:
    a=x

Try to run this code:

list=['e','r','n','t','e','p','s']
for x in list:
print ( list.index(x))

You will get 0123056 instead of 0123456

jlanik
  • 859
  • 5
  • 12
  • I'll bear this in mind, thanks! Is there a way to find the indices of further occurences of an item? – Tobi Nov 22 '18 at 09:23
  • sure, you can do e.g. `all_occurences_of_e = [ i for i in range(len(lst)) if lst[i]=='e' ]` by the way it is probably not a good idea to call your list variable 'list', as 'list' is also the name of the class – jlanik Nov 22 '18 at 11:45