为 nim 游戏编写代码,但空列表的条件不起作用
Writing code for nim game but condition for empty list not working
定义游戏():
print("Welcome to Nim!")
nim_list_1 = ['*', '*', '*']
nim_list_2 = ['*', '*', '*', '*', '*']
nim_list_3 = ['*', '*', '*', '*','*', '*', '*']
player = 1
pile_num = [1,2,3]
print("Pile 1:", *nim_list_1)
print("Pile 2:", *nim_list_2)
print("Pile 3:", *nim_list_3)
while (nim_list_1 and nim_list_2) or nim_list_3 is not None:
# Catches IndexError if we try to pop from empty list
try:
count = 0
while count != pick and pile is not None:
count += 1
pile.pop()
except IndexError:
print("Can't remove sticks from empty pile")
我面临的问题是:即使列表为空,while 循环仍在执行。我希望函数在所有列表变空后立即显示获胜者?任何建议将不胜感激:)
鉴于您设定的目标 "to display the winner as soon as the all the lists become empty",测试 nim_list_3 is not None
是完全错误的!
一个空列表是 "falsy",但这并不意味着它是 None
!所以,只是测试
while (nim_list_1 and nim_list_2) or nim_list_3:
将完成(更接近于)您既定的目标——当列表 3 为空且列表 1 为空或列表 2 为空时退出。这与 "all the lists become empty" 不同,但比针对 None
!-)
的检查更接近
实际说 "exit only when all lists are empty",应该是:
while nim_list_1 or nim_list_2 or nim_list_3:
当然,由于您没有向我们展示列表的更新方式,因此很难猜测您的意思是您所说的 ("all lists become empty") 还是您编写的代码(三个列表的处理方式不同) ).
定义游戏():
print("Welcome to Nim!")
nim_list_1 = ['*', '*', '*']
nim_list_2 = ['*', '*', '*', '*', '*']
nim_list_3 = ['*', '*', '*', '*','*', '*', '*']
player = 1
pile_num = [1,2,3]
print("Pile 1:", *nim_list_1)
print("Pile 2:", *nim_list_2)
print("Pile 3:", *nim_list_3)
while (nim_list_1 and nim_list_2) or nim_list_3 is not None:
# Catches IndexError if we try to pop from empty list
try:
count = 0
while count != pick and pile is not None:
count += 1
pile.pop()
except IndexError:
print("Can't remove sticks from empty pile")
我面临的问题是:即使列表为空,while 循环仍在执行。我希望函数在所有列表变空后立即显示获胜者?任何建议将不胜感激:)
鉴于您设定的目标 "to display the winner as soon as the all the lists become empty",测试 nim_list_3 is not None
是完全错误的!
一个空列表是 "falsy",但这并不意味着它是 None
!所以,只是测试
while (nim_list_1 and nim_list_2) or nim_list_3:
将完成(更接近于)您既定的目标——当列表 3 为空且列表 1 为空或列表 2 为空时退出。这与 "all the lists become empty" 不同,但比针对 None
!-)
实际说 "exit only when all lists are empty",应该是:
while nim_list_1 or nim_list_2 or nim_list_3:
当然,由于您没有向我们展示列表的更新方式,因此很难猜测您的意思是您所说的 ("all lists become empty") 还是您编写的代码(三个列表的处理方式不同) ).