0
def front_x(words):
list2 = []
for word in words:
    if word[0] == 'x':
        list2.append(word)
        words.remove(word)
words.sort()
list2.sort()

return list2 + words




def main():
    print(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']))




if __name__ == '__main__':
    main()

This is my code I'm trying to do this example:

Given a list of strings, return the count of the number of strings where the string length is 2 or more and the first and last chars of the string are the same. Note: python does not have a ++ operator, but += works.

and the output is like this : ['xzz', 'axx', 'bbb', 'ccc', 'xaa']

The problem is the last element on the list don't go to the new list I created. What should I do?

3 Answers3

2
  • You shouldn't change the words when you are iterating through it, otherwise it'll lead to some bugs. You need iterate the copy of words to avoid changing it.
  • You remove the words when word[0] == 'x', which cause the loop end before you want.
  • You can use debug mode in IDE(such as VSCode, PyCharm) to run your code line by line to check what actually happened in runtime.

example code:

def front_x(words):
    list2 = []
    for word in words.copy():
        if word[0] == 'x':
            list2.append(word)
            words.remove(word)
    words.sort()
    list2.sort()

    return list2 + words

def main():
    print(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']))

main() 

result:

['xaa', 'xzz', 'axx', 'bbb', 'ccc']
leaf_yakitori
  • 2,232
  • 1
  • 9
  • 21
0

This is because you are removing the element from the same list you are iterating . After removing an element from list , element position shift. When iteration pointer is on second last element list changes from ['bbb', 'ccc', 'axx', 'xzz', 'xaa'] to ['bbb', 'ccc', 'axx', 'xaa']. Thus iteration pointer now points to last element .

-2

In this problem the question wants you to use 2 different things:

  1. len function
  2. list indexing

len

len returns the size of a container. A container can be a str, list, tuple, etc.

To check if the length of the given string is equal or bigger then 2.

if len(word) >= 2:

indexing

Accessing the first element of a container (in your example a string) is easy. You can get the 0th element like:

word[0]

But you will need to get the last element of a container and your strings can change in length. So you must come with a method to get the last element of the container.

You, again, can use the len function. like:

last_char = word[len(word) - 1]

or you can use negative indexes.

last_char = word[-1]
MSH
  • 1,743
  • 2
  • 14
  • 22