【发布时间】:2018-09-28 00:41:49
【问题描述】:
我的函数应该使用一个元组列表并返回车辆达到或超过 n 所需的天数,从列表中的第一天开始,只使用一个 while 循环和一个 return 语句。
def days_to_reach_n_vehicles(vehicle_records, n):
"""Returns number of days taken to reach or exceed a total of n vehicles"""
cumulative_total = 0
num_days = 0
index = 0
while index < len(vehicle_records):
cumulative_total += vehicle_records[index][1]
index += 1
num_days += 1
if cumulative_total >= n:
break
return num_days
它给了我以下测试代码的正确输出 2:
some_records = [('2010-01-01',1),
('2010-01-02',2),
('2010-01-03',3)]
days = days_to_reach_n_vehicles(some_records, 3)
print(days)
但是如果在vehicle_records 中的最后一天没有到达n 辆车,它需要返回None。我无法让它为下一个测试数据返回 None,有人可以告诉我我需要修复什么吗?
some_records = [('2010-01-01',1),
('2010-01-02',2),
('2010-01-03',3)]
days = days_to_reach_n_vehicles(some_records, 40)
print(days)
【问题讨论】:
-
我的测试代码输出为 1
-
什么情况下不应该返回None?
-
我认为您需要将
return num_days移回缩进。目前它每次都返回第一次迭代。或者取决于你想要什么 - 你可能想把它放在你的if cumulative_total >= n:块中。编辑:我看到你现在已经改变了。 -
return num_days if cumulative_total >= n else None应该是你要找的。span> -
将您的
break替换为return num_days。并且没有第二次返回 - 该函数将自动返回None。这应该可以解决它。
标签: python python-3.x list while-loop tuples