Python:为什么这个程序没有工作?

时间:2015-03-18 18:39:52

标签: python combinations

我制作了一个程序,用于查找从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()

由于某种原因,当我运行程序时没有任何反应,我找不到任何逻辑错误,那么错误呢?

1 个答案:

答案 0 :(得分:0)

工作代码:

import random

number_of_combinations = 0
all_lists = []
list_to_check = []




def a_function():
  global number_of_combinations
  global list_to_check
  global all_lists

  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_of_combinations == 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
  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()
  else:
    a_function()

a_function()

编辑:     all_lists.append(list_to_check[:]) #add it to the all_list(如果您之后销毁了内容,则需要添加列表副本。 elif number_for_list not in list_to_check: a_function() else: a_function() 如果number在列表中(else分支),则需要生成新的。