【发布时间】:2015-12-16 21:25:43
【问题描述】:
好的,对编码和 python 来说非常非常新。
此脚本的目标:您必须掷多少次“x”骰子才能使它们都得到相同的值?
这是它试图做的事情: 从用户那里拿一些骰子 模拟掷骰子 如果所有骰子都匹配,则打印尝试成功的次数,如果不匹配,请重试。
会发生什么:
如果用户输入少量骰子,1-4 左右,它可以正常工作。
一旦用户输入 5 个(或更多)骰子,就会遇到“调用 python 对象时超出最大递归深度”错误。它似乎是调用 random.randint 的一部分
鉴于我不确定为什么递归变得无限,我希望有人能给我一些关于如何避免此错误的指导。我试图评论我的代码以使其有意义(至少对我而言)。
如果重要的话,我正在 Enthought Canopy 环境中使用 python 2.6。
import random
#create the empty list to store values
dierolls = []
#used to roll ythe dice
def diceroll():
return random.randint(1,6)
#gets user input to determine how many dice we are rollin
def askfornumofdicetoroll():
return int(input("How many dice should we roll?"))
#fills the dierolls list with the appropriate
def fillthelist(dicecount):
#empty the list and start fresh each iteration
dierolls[:] = []
#input a die roll for each die the user says to roll
for i in range(0,dicecount):
dierolls.append(diceroll())
#print dierolls #used to check that this code was running
return dierolls
#what to do when all the dice match
def wongame(attempts):
print("You matched all the dice in", attempts , "tries")
#compares all the items in the list, and see's if they match
def comparelist(dicetoroll,attempts):
fillthelist(dicetoroll)
#print statement used to make sure this was running
print dierolls
#print statment used to see if this section of code was running
print(all(dierolls[0] == elem for elem in dierolls))
#gives a check to make sure the code is running and not stopped by
#printing a result every 100 attempts
if attempts%100 == True:
print attempts
else:
pass
#does the actual check to see if all items in the list are the same
if all(dierolls[0] == elem for elem in dierolls):
#if all items in list are the same, go to the results function
wongame(attempts)
else:
#increment the attempts counter, and try again
attempts += 1
comparelist(dicetoroll, attempts)
#runs the program
def main():
attempts = 1
dicetoroll = askfornumofdicetoroll()
comparelist(dicetoroll,attempts)
【问题讨论】:
-
你有有限的,但在
comparelist中非常长递归,你不应该这样编码 - 如果你应该多次重复代码使用循环 不是递归。
标签: python python-2.7