【发布时间】:2015-05-21 17:10:03
【问题描述】:
我编写了一个程序来查找从 0 到 3 的数字的所有组合,可能的列表数量为 24 (4! = 24)
import random
number_for_list = 0
number_of_combinations = 0
all_lists = []
list_to_check = []
def a_function():
number_for_list = random.randrange(4) #generate a random number
if len(list_to_check) == 4: #check if 4 different numbers are in the list
if list_to_check in all_lists: #if that list (with 4 numbers) already exists in all_lists remove it and go back to a_function
del list_to_check[:]
a_function()
else: #if that list isnt in all_lists
all_lists.append(list_to_check) #add it to the all_lists
number_of_combinations += 1 #raise number_of_combinations
del list_to_check[:] #delete the list_to_check and go back to a_function
a_function()
elif number_for_list not in list_to_check: #if number_for_list isn't in the list_to_check
list_to_check.append(number_for_list) #add it to the list_to_check and go back to a function
a_function()
elif number_for_list == 24: #if number_of_combinations equals 24 then it should print all lists
print('I found all the combinations') #and stop the function
print(all_lists)
return
a_function()
由于某种原因,当我运行程序时没有任何反应,而且我找不到任何逻辑错误,那是什么问题?
【问题讨论】:
-
猜想:你的
if子句没有通过,你的两个elif子句也没有通过,所以函数只是安静地结束。 -
没有一个 if 条件为真。
-
我找不到任何逻辑错误。再看一遍。您从一个空列表开始,
number_for_list将是0、1、2或3。在这种情况下,您的任何条件将如何匹配?如果其中一个数字在在列表中怎么办? -
我真的不明白,什么没有通过,我需要改变什么? @Martijin 是的,我创建了一个空列表,因为它需要首先声明,并且 number_for_list 只能是 0、1、2、3(生成一个数字会生成从零到 x - 1 的数字(在我的情况下,它是从 1 到 4)将从 0 变为 3)。
-
顺便说一下,考虑放弃所有这些代码,只做
import itertools; print list(itertools.permutations(range(4)))
标签: python combinations