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")
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With