python - 为什么所有值都附加到列表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]
解决方案
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))
推荐阅读
- javascript - window.requestAnimationFrame() 是如何工作的?
- javascript - 从 Firebase 上传和下载
- laravel - Laravel:从数据库中显示 HTML 代码和 Laravel 语法?
- javafx - JavaFX中单元格的依赖于单元格的外观
- jquery - 使用后退按钮隐藏显示 li 子元素
- ibm-mq - 在 IBM MQ 中执行读取操作后,消息是否会从队列中删除?
- swift - HLS 流使用 AVAssetResourceLoaderDelegate TS 片段请求缺少 Cookie 标头
- php - PRIVMSG 从 php 到 IRC 服务器
- scala - 列表元素的所有组合,同时每个元素保持位置
- css - 通过父 div 使 div 透明