Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a list contains either 3 even or 3 odd values next to each other?

How do you determine if a list contains either 3 even or 3 odd values all next to each other?

Example lists (True, False, True):

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

Closest code:

evenOdd = []

while True: 
    try:
        n = int(input())
        evenOdd.append(n)
    except:
        break

for x in evenOdd:
   if x % 2 == 0:
       print("True")
like image 915
Lara Avatar asked Dec 10 '22 05:12

Lara


2 Answers

Here is some code. This is considered more "pythonic" than iterating over indices--this iterates over consective-triples, using the zip function. This will give an error if the list has fewer than three items--you can add that error check. The zip function stops when one of the iterables runs out of values, which is exactly what we want here.

def three_evens_or_odds(alist):
    for a, b, c in zip(alist, alist[1:], alist[2:]):
        if (((a & 1) and (b & 1) and (c & 1)) or
            ((a & 1 == 0) and (b & 1 == 0) and (c & 1 == 0))):
            return True
    return False

print(three_evens_or_odds([2, 1, 3, 5]))
print(three_evens_or_odds([2, 1, 2, 5]))
print(three_evens_or_odds([2, 4, 2, 5]))

Or, even shorter (borrowing an idea from @jdehesa which I should have thought of on my own, so upvote his answer as I did),

def three_evens_or_odds(alist):
    for a, b, c in zip(alist, alist[1:], alist[2:]):
        if a & 1 == b & 1 == c & 1:
            return True
    return False

print(three_evens_or_odds([2, 1, 3, 5]))
print(three_evens_or_odds([2, 1, 2, 5]))
print(three_evens_or_odds([2, 4, 2, 5]))

The printout from that is

True
False
True
like image 115
Rory Daulton Avatar answered Dec 12 '22 18:12

Rory Daulton


You can use itertools.groupby():

from itertools import groupby

def check_list(lst):
    for k, g in groupby(lst, key=lambda x: x % 2):
        if len(list(g)) == 3:
            return True
    return False    

print(check_list([2, 1, 3, 5]))  # True
print(check_list([2, 1, 2, 5]))  # False
print(check_list([2, 4, 2, 5]))  # True

This can be easily adjusted for any group size.

like image 24
Eugene Yarmash Avatar answered Dec 12 '22 18:12

Eugene Yarmash