I was told to solve a problem in which I would have to find out the number of 4-digit numbers which are all composed of odd digits. I tried the following python code:
A 4 digit number that is composed only of odd digits can only use the digits 1
, 3
, 5
, 7
and 9
. That gives you 5 to the power 4 is 625 different numbers. That didn't require trying them all out.
You can still do that of course, using itertools.product()
for example:
from itertools import product
print sum(1 for combo in product('13579', repeat=4))
because product('13579', repeat=4)
will produce all possible combinations of 4 characters from the string of odd digits.
Your code needs to test if all digits are odd; break out early if any digit is not odd:
new_list =[] # A list which holds the numbers
for a in range(1111,10000):
for b in str(a):
if int(b) % 2 == 0:
break
else:
# only executed if the loop wasn't broken out of
new_list.append(a)
You could use the all()
function with a generator expression for that test too:
new_list = []
for a in range(1111,10000):
if all(int(b) % 2 == 1 for b in str(a)):
new_list.append(a)
which then can be collapsed into a list comprehension:
new_list = [a for a in range(1111,10000) if all(int(b) % 2 == 1 for b in str(a))]