我正在使用Python 3.6在Jupyter Notebook中工作。我不明白为什么所有的值都被附加到winning_numbers而不是应有的lost_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]
答案 0 :(得分:0)
问题在于您在or
语句中组织if
的方式:
if x-1 or x/2 in losing_numbers:
这意味着:
if (x-1) or (x/2 in losing_numbers):
由于对于x
的所有整数值(除1之外,x-1
为truthy
),该值始终为true,并且x
将附加到{{1} }。
您应该将其重写为:
winning_numbers
或:
if x-1 in losing_numbers or x/2 in losing_numbers: