python - 无法为元组列表中的数据返回无

标签 python python-3.x list while-loop tuples

我的函数应该获取一个元组列表,并返回车辆达到或超过 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/

相关文章:

Python:urlretrieve PDF 下载

python - 如何防止在使用 python 的 Linux 中使用 "ctrl+c"终止正在运行的程序?

android - 我们如何为基于 python 的应用程序创建 android apk

python - 使用 .loc 和 OR 运算符返回 ValueError

python - 将已见集用于有向图与无向图

python - 在 python 中索引向量列表

python - 从列表 : pythonic way 的列表中删除项目

python - python 并行化递归

python - 从批处理文件运行 python 脚本时出现 ModuleNotFoundError

list - 在Scheme中的列表中添加元素