我的函数应该获取一个元组列表,并返回车辆达到或超过 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)
最佳答案
也许您需要返回 num_days if cumulative_total >= n else None
。
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 if cumulative_total >= n else None
关于python - 无法为元组列表中的数据返回无,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49888412/