This sequence, containing from 2 to 20 words, in each of which is from 1 to 8 lower case, between adjacent words - at least one space, followed by the last word - a period.

Implement the display on the screen of those words of the sequence that are different from the last word and satisfy the properties of symmetry.

I can not understand why the code does not work correctly:

Text=input("ведите слова") print(Text,end=".") if len(Text.split())>20: print() print("введите меньше слов") elif len(Text.split())<2: print() print("введите больше слов") Text_1=Text.split() for i in Text_1: if i==Text_1[-1]: Text_1.remove(i) elif Text_1[0]==Text[-1]: Text_1.remove[0] print() print(Text_1,end=".") print() for b in Text_1: b=b.split() if b.reverse not in Text_1: Text_1.remove(b)#ValueError: list.remove(x): x not in list-ошибка print(Text_1) 
  • 2
    Please add an example of the source data and the desired result. - strawdog

1 answer 1

Main problem of your program (twice):

  • In the for loop, go through the same list, from which you delete members from it and change it .

    It is necessary to go through a copy of the list (which you can simply get by creating a segment with all the elements , that is, adding [:] for its name.)

The second problem is that it is impossible to apply the .reverse() method to a string - you first need to translate it into a list of characters (for example, the list() function).

But the third is that your program still works after entering the wrong number of words, only it gives a message about it. It is then necessary (and again) to ask the question (in the while ) until the word count is correct.

I reworked your program a little bit and used more convenient names for variables, only with lowercase letters - see PEP 8 - a guide to writing Python code - and put spaces somewhere (see there).

 while True: text = input("Ведите слова: ") words = text.split() if len(words) > 20: print("Введите меньше слов.") print() continue # прекратить, а снова задать вопрос elif len(words) < 2: print("Введите больше слов.") print() continue break # прекратить весь цикл last_word = words[-1][:-1] # [:-1] для удаления точки words = words[:-1] # последнее слово уже не надо for word in words[:]: # [:] строит копию списка if word == last_word: words.remove(word) for word in words[:]: # [:] строит копию списка letters = list(word) letters.reverse() reversed_word = "".join(letters) if word != reversed_word: words.remove(word) print(words) 

Note:

Instead of a pair of teams

 last_word = words[-1][:-1] # [:-1] для удаления точки words = words[:-1] # последнее слово уже не надо 

can use the command

 last_word = words.pop()[:-1]