使用此代码模拟在骰子游戏中选择第一个玩家 但有时会引发最大深度误差 我该如何解决? 是代码还是语言的问题?
import random
u1 = random.randint(1, 6)
u2 = random.randint(1, 6)
u3 = random.randint(1, 6)
u4 = random.randint(1, 6)
users = [u1, u2, u3, u4]
roll_outcome = []
tie_outcome = []
def outcome():
if len(roll_outcome) == 1:
if roll_outcome[0] == 0:
print("u1 is P1")
elif roll_outcome[0] == 1:
print("u2 is P1")
elif roll_outcome[0] == 2:
print("u3 is P1")
elif roll_outcome[0] == 3:
print("u4 is P1")
else:
if tie_outcome != 0:
tie_outcome.clear()
elif len(roll_outcome) > 1:
for i in range(len(roll_outcome)):
if i == 0:
u10 = random.randint(1, 6)
tie_outcome.append(u1)
elif i == 1:
u20 = random.randint(1, 6)
tie_outcome.append(u20)
elif i == 2:
u30 = random.randint(1, 6)
tie_outcome.append(u3)
elif i == 3:
u40 = random.randint(1, 6)
tie_outcome.append(u4)
roll(tie_outcome)
def roll(enterying_data):
for i in range(len(enterying_data)):
if max(enterying_data) == enterying_data[i]:
roll_outcome.append(i)
outcome()
roll(users)
馅料: ....................................................
答案 0 :(得分:0)
两者都有。
您的代码使用递归循环-roll
调用outcome
,后者调用roll
,依此类推,这可能发生无数次。在某些语言中,您可以通过由编译器或解释器执行的尾调用优化来摆脱这种情况。 Python没有这种优化,因此递归调用在Python程序中的深度是有限的。
幸运的是,使该循环迭代并不难(这意味着它可以无限次循环而无需无限深的堆栈)。
def outcome():
if len(roll_outcome) == 1:
if roll_outcome[0] == 0:
print("u1 is P1")
elif roll_outcome[0] == 1:
print("u2 is P1")
elif roll_outcome[0] == 2:
print("u3 is P1")
elif roll_outcome[0] == 3:
print("u4 is P1")
return None # done!
else:
if tie_outcome != 0:
tie_outcome.clear()
elif len(roll_outcome) > 1:
for i in range(len(roll_outcome)):
if i == 0:
u10 = random.randint(1, 6)
tie_outcome.append(u1)
elif i == 1:
u20 = random.randint(1, 6)
tie_outcome.append(u20)
elif i == 2:
u30 = random.randint(1, 6)
tie_outcome.append(u3)
elif i == 3:
u40 = random.randint(1, 6)
tie_outcome.append(u4)
return tie_outcome # roll again
def roll(enterying_data):
for i in range(len(enterying_data)):
if max(enterying_data) == enterying_data[i]:
roll_outcome.append(i)
return outcome()
while users is not None:
users = roll(users)
请注意,这里仍然存在一个问题,即解决联系的逻辑并没有真正起作用,因此代码此时将进入无限循环,但至少不会得到{{1} }……
FWIW,如果此代码的目的是从四个用户中随机选择P1,则可以使用以下命令更简单地完成此操作:
DepthError