0
Text = input('please enter your text')
l = [str(x) for x in Text.split()]
count = 0
for item in l:
    for i in range(1,len(item)):
        if item[i-1] == item[i]:
            count +=1
    if count <1:
        l.remove(item)
    count = 0
print (l)

the goal is : if we have a text : 'baaaaah mooh lpo mpoo' to get a list with elements they have 2 successive same characters, in this case ['baaaaah', 'mooh', 'mpoo' ]

the program is working with the mentioned example

if i use this one it's not working : 'hgj kio mpoo'

thank you

MSK
  • 33
  • 5

2 Answers2

1

(complex)One liner:

>>> def successive_items(s):
        return [x for x in s.split() if any(x[i]==x[i-1] for i in range(1,len(x)))]

>>> successive_items('baaaaah mooh lpo mpoo')
['baaaaah', 'mooh', 'mpoo']
>>> successive_items('hgj kio mpoo')
['mpoo']

In case of your code, you should not modify the list you are iterating over. Say, for example, lets have an array:

a = [1,2,3,4,5]

Now, if you iterate and remove elements (inside the loop), you would expect a to be empty. But let's check out:

>>> a = [1,2,3,4,5]
>>> for item in a:
        a.remove(item)

>>> a
[2, 4]

See? It is not empty. This is better explained here.

Your program is not working for the second case because of list modification. Here is how:

  1. Initially your list had ['hgj','kio','mpoo'].
  2. After reading the first element you removed hgj. So the list now becomes ['kio','mpoo'].
  3. The loop iterates the 2nd element next, and it gets mpoo (in the modified list);
  4. kio was never read.
mshsayem
  • 17,557
  • 11
  • 61
  • 69
0

This might help:

sentence = input("please enter your text")

words = sentence.split()

answers = []
for each_word in words:
    for idx in range(1, len(each_word)):
        if each_word[idx] == each_word[idx-1]:
            answers.append(each_word)
            break

print(answers)

In your code, you are iterating over a list and at the same time you are modifying that very same list(by deleting elements from it), for more explanation see this answer

tkhurana96
  • 919
  • 7
  • 25