[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Problem with rearanging list with paired letters next to each others

On 2020-11-11 01:26, Bischoop wrote:
> Can anybody help?Here's the code that gives me a hedeache for second day
> If I have letter_list = ["a","a",,"b","b","c","c"] it's working
> correctly but if I have three or more of any letters for
> example:letter_list = ["a","a","a","b","b","c","c"], I'm ending up with
> some pairs somewhere.
> I took another way approach today:, was thinking
> about iterating and checking if neighbour characters won't make a pair
> but I've end up with error:
> if x != letter_list[i+1] and letter_list[i-1]:
> IndexError: list index out of range
> andin addition: got 4 "a" (had 3only) and missing 1 "b" :-/
Points to note in your first code:

1. Modifying a list while iterating over it is a bad idea.

2. You're modifying the list that you're passing in and also returning 
it. That's a bad idea. Either modify it in place or modify and return a 

3. The line:

        m = (letter_list.index(x))

    returns the position of the first occurrence of x.

Points to note in your second code:

1. (See above)

2. (See above)

3. (See above)

4. 'i' goes from 0 to len(letter_list)-1, so i+1 goes from 1 to 
len(letter_list), but the maximum index permitted by letter_list is 
len(letter_list)-1, hence letter_list[i+1] will raise IndexError on the 
last iteration.

5. 'i' goes from 0 to len(letter_list)-1, so i-1 goes from -1 to 
len(letter_list)-2. letter_list[-1] returns the last (final) letter in 
the list, and it's treated as a true.

6. This:

        x != letter_list[i+1] and letter_list[i-1]

    is checking whether:

        x != letter_list[i+1]

    is true and also whether:


    is true.