首页 > 解决方案 > 为什么所有值都附加到列表winning_numbers?

问题描述

我正在使用 Python 3.6 在 Jupyter Notebook 中工作。我不明白为什么所有的值都被附加到winning_numbers 而不是它们应该的loose_numbers。

我的代码:

import numpy as np

winning_numbers = []
losing_numbers = []

limit = 11

for x in range(1, limit):

    if x%2 == 0:

        if x-1 or x/2 in losing_numbers:
            winning_numbers.append(x)

        elif x-1 and x/2 in winning_numbers:
            losing_numbers.append(x)

    if x%2 == 1:

        if x-1 == 0:
            winning_numbers.append(x)

        elif x-1 or (x-1)/2 in losing_numbers:
            winning_numbers.append(x)

        elif x-1 and (x-1)/2 in winning_numbers:
            losing_numbers.append(x)

print("Winning Numbers: ", winning_numbers)
print("Losing Numbers: ", losing_numbers)

我的输出是:

Winning Numbers:  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Losing Numbers:  []

输出应该是:

Winning Numbers: [1, 3, 4, 5, 7, 9]
Losing Numbers: [2, 6, 8, 10]

标签: pythonpython-3.xif-statementjupyter-notebook

解决方案


The problem is the way your organized the or in your if statement:

if x-1 or x/2 in losing_numbers:

This means:

if (x-1) or (x/2 in losing_numbers):

Since for all integer values of x except for 1, x-1 is truthy, this will always evaluate to true and x will be appended to winning_numbers.

You should rewrite it as:

if x-1 in losing_numbers or x/2 in losing_numbers:

or:

if any(k in theQuestion for k in (x-1, x/2))

推荐阅读