python - Python 我明确返回 None 但什么也没得到
问题描述
我在基本情况下明确返回None
,但 doctest 告诉它什么都没有。
这是我的代码:
def find_triple(ilist):
""" Find a triple of integers x, y, z in the list ilist such that x + y = z.
Return the tuple (x, y). If the triple does not exist, return None.
>>> find_triple([4,5,9]) in [(4,5), (5,4)]
True
>>> li = [(30,70), (70,30), (20,50), (50,20), (20,30), (30,20)]
>>> find_triple([20,40,100,50,30,70]) in li
True
>>> find_triple([6,11,7,2,3])
None
>>> find_triple([1, 1, 3])
None
"""
# define a yield function to reduce the cost of time and space
def yield_pair(ilist):
""" enumerate all the two pairs in the list.
>>> g = yield_pair([4,5,9])
>>> next(g)
(4, 5)
>>> next(g)
(4, 9)
>>> next(g)
(5, 9)
>>> next(g)
Traceback (most recent call last):
...
StopIteration
"""
for i in range(len(ilist) - 1):
for j in range(i, len(ilist) - 1):
yield (ilist[i], ilist[j + 1])
# first turn the ilist into a set, so the `in` operation is much more efficient
iset = set(ilist)
g = yield_pair(ilist)
while True:
try:
pair = next(g)
if sum(pair) in iset:
return pair
except StopIteration:
return None # ******** problems here ****************
except:
return None # ******** verbose I just try to show that it does not return None *******
这是我的错误信息:
Failed example:
find_triple([6,11,7,2,3])
Expected:
None
Got nothing
解决方案
REPL 总是忽略None
作为返回值,不打印任何内容。跳过该行的输出或显式打印返回值。
推荐阅读
- arrays - 如何对对数组进行排序
在 C++ 中? - node.js - 如何在快速请求参数上获得预期类型
- python - 在 django rest 框架中返回对成功 POST 请求的自定义响应
- laravel-blade - Laravel Blade @includeWhen 给了我未定义的变量错误
- postgresql - /models 文件夹下表中的更改字段不会更新表架构
- excel - 如何在 With..End With 块中复制值(而不是格式)?
- git - 实现 FTP GitHub Action 逐个文件上传
- javascript - 正则表达式验证错误,它反转值 - javascript
- c# - 我如何修复问题接口 C#(控制台 .NET Core):CS0535 和 CS1061
- html - 如何使用 CSS 为 div 的背景图像设置不透明度或降低亮度