Conditional loop in python

list=['a','a','x','c','e','e','f','f','f'] i=0 count = 0 while count < len(list)-2: if list[i] == list[i+1]: if list [i+1] != list [i+2]: print list[i] i+=1 count +=1 else:print "no" else: i +=1 count += 1 

I get:

  else:print "no" ^ IndentationError: unexpected indent 

I am only trying to print elts that match the next element, but not the next element. I'm new to Python and I'm not sure why this is not working.

+4
source share
2 answers

Here's the copied code (added count += 1 after else-clause to make sure it completes):

 list=['a','a','x','c','e','e','f','f','f'] i=0 count = 0 while count < len(list)-2: if list[i] == list[i+1]: if list [i+1] != list [i+2]: print list[i] i+=1 count +=1 else: print "no" count += 1 else: i +=1 count += 1 

A more advanced solution using itertools is more compact and simpler in law:

 from itertools import groupby data = ['a','a','x','c','e','e','f','f','f'] for k, g in groupby(data): if len(list(g)) > 1: print k 
+7
source

The code works for me without errors (although you are stuck in a loop). Make sure you do not mix tabs and spaces.

+2
source

Source: https://habr.com/ru/post/1481583/


All Articles