我试图编写一个模拟囚徒困境的程序(为了我自己的研究目的),而且我在每一轮游戏中都无法生成随机计算机选择。这是我目前的while循环:
user_points = 0
N_points = 0
games_played = 0
while games_played != games:
print("Games played: ",games_played)
s = choice(["confess","remain silent"])
choice = input("Do you choose to confess to the crime or to remain silent? ")
if choice.lower() == "confess" or choice.lower() == "remain silent":
print("You chose to %s, and N chose to %s." % (choice,s))
else:
print("Please choose to either confess or remain silent.")
if choice.lower() == "confess" and s == "confess":
print("You have both confessed. You both get 9 years in prison.")
user_points -= 2
N_points -= 2
elif choice.lower() == "confess" and s == "remain silent":
print("You confessed while N remained silent. You walk free while N \
spends the next 7 years in jail.")
N_points -= 4
elif choice.lower() == "remain silent" and s == "remain silent":
print("Fine then...Neither of you wants to talk, but you both still \
get a year each for weapons charges.")
user_points += 1
N_points += 1
elif choice.lower() == "remain silent" and s == "confess":
print("You remained silent, but N confessed. You'll spend the next 7 \
years in jail while N walks free.")
user_points -= 4
games_played += 1
print("Your score is %s." % (user_points))
print("N's score is %s." % (N_points))
else:
print("Final Score: You scored %s points. N scored %s points." % (user_points,N_points))
if user_points > N_points:
return "Congrats! You have won the Prisoner's Dilemma."
elif user_points == N_points:
return "You and N tied. Neither of you wins the Prisoner's Dilemma."
else:
return "You have lost the Prisoner's Dilemma."
当我运行代码时,出现以下错误:
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
prisonerDilemma()
File "/Users/stephenantonoplis/Documents/prisonersdilemma.py", line 167, in prisonerDilemma
s = choice(["confess","remain silent"])
TypeError: 'str' object is not callable
有谁知道如何解决这个问题?我可以在while循环之外定义s,但是计算机会在每一轮使用相同的选项,这不是随机的。
答案 0 :(得分:4)
您正在为choice
分配一个字符串,该字符串会影响它用于指向的函数定义。将其命名为其他内容,或坚持random.choice
。