Print All Even Numbers In A List Until A Given Number
I am just beginning to dabble in Python, and have started to go through the chapters on learnpython.org. In the 'Loops' chapter, I have solved the challenge with the following code
Solution 1:
That's what else
and elif
are for:
for x in numbers:
if x == 237:
break
elif x % 2 == 0:
print x
Solution 2:
Another method is using itertools
which always comes in useful some way or another:
>>> from itertools import takewhile, ifilter
>>> not_237 = takewhile(lambda L: L != 237, numbers)
>>> is_even = ifilter(lambda L: L % 2 == 0, not_237)
>>> list(is_even)
[402, 984, 360, 408, 980, 544, 390, 984, 592, 236, 942, 386, 462, 418, 344, 236, 566, 978, 328, 162, 758, 918]
So we create a lazy iterator that stops at 237, then take from that even numbers
Solution 3:
This is also possible:
try:
i = numbers.index(237)
except:
i = len(numbers)
for n in numbers[:i]:
if not n%2:
print n
Solution 4:
Im just going throug this exercise in my "learning the basis thing" and i came out with a similar but somehow worse solution, patrik :(
x = 0
for loop in numbers:
if (numbers[x]) % 2 ==0:
print (numbers[x])
x = x+1
if (numbers[x]) ==237:
break
else:
x =x+1
continue
Solution 5:
you can do that using list comprehension
The solution would be like this:
numbers = [x for ind,x in enumerate(numbers) if x % 2== 0 and numbers[ind+1]!=237 ]
Post a Comment for "Print All Even Numbers In A List Until A Given Number"