Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional loop in python

Tags:

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'm getting:

    else:print "no"
   ^
 IndentationError: unexpected indent

I'm trying to only print the elts that match the following element, but not the element following that. I'm new to Python, and I'm not sure why this isn't working.

like image 520
whatever Avatar asked Jan 14 '23 08:01

whatever


2 Answers

Here is the fixed-up code (added a count += 1 after the else-clause to make sure it terminates):

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 easier to get right:

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
like image 153
Raymond Hettinger Avatar answered Jan 21 '23 05:01

Raymond Hettinger


The code works for me without error (although you get stuck in a loop). Make sure you are not mixing tabs and spaces.

like image 20
cogsmos Avatar answered Jan 21 '23 04:01

cogsmos