I'm trying to make it a habit of creating list comprehensions, and basicly optimize any code I write. I did this little exercise to find if all digits in a given number is even, when trying to create a list with for loops and if statements i ran into a problem with "continue" & "break". Can i even insert those flow controls into a list?
I'd love to know how much i can shorten any piece of code. Here's what i wrote, i'd love to get feedback from you guys.
numbers = [str(x) for x in range(0, 10000)]
def is_all_even(nums):
temp_lst = []
evens_lst = []
for x in nums:
for y in x:
if int(y) % 2 == 0:
temp_lst.append(str(y))
continue
else:
break
if len(''.join(temp_lst[:])) == len(x):
evens_lst.append(''.join(temp_lst[:]))
del temp_lst[:]
print(evens_lst)
You can use a list comp,using all to find the numbers that contain all even digits:
print([s for s in numbers if all(not int(ch) % 2 for ch in s)])
all
will short circuit on finding any odd digit.
If you don't want to store all the numbers in memory at once you can use a generator expression:
evens = (s for s in numbers if all(not int(ch) % 2 for ch in s))
To access the numbers you just need to iterate over evens:
for n in evens:
print(n)
You could also use filter for a functional approach which returns an iterator in python 3:
In [5]: evens = filter(lambda x: all(not int(ch) % 2 for ch in x), numbers)
In [6]: next(evens)
Out[6]: '0'
In [7]: next(evens)
Out[7]: '2'
In [8]: next(evens)
Out[8]: '4'
In [9]: next(evens)
Out[9]: '6'
[x for x in range(10000) if all(c in '02468' for c in str(x))]
Rather than sending the whole list of numbers to the function, you can send just one number to a function and then use the list comprehension to apply it to your list.
def is_all_even(num):
return all(ch in '02468' for ch in str(num))
print([n for n in range(10000) if is_all_even(n)])
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