正在为nim游戏编写代码,但空列表的条件不起作用

2024-06-17 13:45:11 发布

您现在位置:Python中文网/ 问答频道 /正文

def game():

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循环仍在执行。我希望函数在所有列表变空时立即显示获胜者?如有任何建议,我们将不胜感激:)


Tags: andtononeiscountnotpoplist
1条回答
网友
1楼 · 发布于 2024-06-17 13:45:11

考虑到你设定的目标“当所有列表都变为空时显示获胜者”,测试nim_list_3 is not None是完全错误的!你知道吗

空列表是“falsy”,但这并不意味着它是None!所以,只是测试一下

while (nim_list_1 and nim_list_2) or nim_list_3:

当列表3为空,或者列表1为空,或者列表2为空时,将完成(更接近)您所陈述的目标。这与“所有列表都变空”不同,但它比检查None更接近!-)你知道吗

要实际声明“仅当所有列表为空时退出”,应为:

while nim_list_1 or nim_list_2 or nim_list_3:

当然,由于您没有向我们展示列表是如何更新的,因此很难猜测您实际上是指您所说的内容(“所有列表变为空”)还是您所编写的代码(三个列表的处理方式不同)。你知道吗

相关问题 更多 >