我有兴趣弄清楚每个数字在5位数的数字范围内出现的次数,如01234,01243,01324等.... 我知道发生的时间是120次 目前我已经用很多for循环和很多ands编程了它。 正如你在代码中看到的那样
number = 5
for a in range(number):
for b in range(number):
for c in range(number):
for d in range(number):
for e in range(number):
if (a != b and a != c and a != d and a != e and
b != c and b != d and b != e and c != d and
c != e and d != e):
print ('{}{}{}{}{}'.format(a, b, c, d, e))
是否有一种不同的,更好的方式来编写上面的代码?
映入眼帘,
超级苍蝇
答案 0 :(得分:0)
有人建议使用itertools。以下是要使用的代码:
from itertools import permutations
#generator
factorials = permutations(set(range(5)))
for fact in factorials:
print(fact)
如果您不想使用itertools,但想生成每个字符串,可以使用列表推导将所有字符串放在一行中。
rn = range(number)
number= 5
sequences = [(a,b,c,d,e) for a in rn for b in rn for c in rn for d in rn for e in rn if a != b and a!= c and a!= d and a!= e and b!= c and b!=d and b!=e and c!=d and c!= e and d!= e]
或者,您可以定义一种递归创建新列表和追加项目的方法
def rGenFactorials(L, leng=5, collected = [], restrictions=set()):
# base case
if len(L) == leng:
collected.append(L)
return
#induction
options = set(range(leng))
options -= restrictions
for op in options:
# copy restrictions
r = set(restrictions)
# add new restriction
r.add(op)
# copy list
l = L[:]
# append unused int
l.append(op)
# recursive invocation
rGenFactorials(L=l,collected = collected, restrictions=r)
C = []
rGenFactorials([], collected = C)
for c in C:
print(c)