[Solved] Lists, conditionals and loops don’t give the result expected [closed]


This line:

i = word.find(letter)

always finds the first occurrence of letter in word, and this line:

start = indeces.index(i)

always finds the first occurrence of i in indeces. Then, this line:

index=word.find(letter,start)

includes start, so just finds the same letter straight away!

The only way to make your current code work would be to introduce a while loop, and start after the last occurrence:

for letter in word:
    i = word.find(letter)
    while i in indeces:
        i = word.find(letter, i+1)
    indeces.append(i)

This keeps looking until it finds a new i for the current letter. If i isn’t in indeces to start with, the loop never runs.


That being said, this is a hugely inefficient approach; if you want the indices use range:

>>> range(len("patata"))
[0, 1, 2, 3, 4, 5]

and if you want the letters and their indices use enumerate:

>>> list(enumerate("patata"))
[(0, 'p'), (1, 'a'), (2, 't'), (3, 'a'), (4, 't'), (5, 'a')]

1

solved Lists, conditionals and loops don’t give the result expected [closed]