仅由奇数位组成的 4 位数字只能使用数字1
, 3
, 5
, 7
and 9
。 5 的 4 次方就是 625 个不同的数字。这并不需要把它们都尝试一遍。
当然,您仍然可以这样做,使用itertools.product()
例如:
from itertools import product
print sum(1 for combo in product('13579', repeat=4))
because product('13579', repeat=4)
将从奇数字符串中产生 4 个字符的所有可能组合。
您的代码需要测试是否all数字为奇数;如果有任何数字,则尽早突破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)
你可以使用all()
函数也带有用于该测试的生成器表达式:
new_list = []
for a in range(1111,10000):
if all(int(b) % 2 == 1 for b in str(a)):
new_list.append(a)
然后可以将其折叠为列表理解:
new_list = [a for a in range(1111,10000) if all(int(b) % 2 == 1 for b in str(a))]