Python 程序用于找出可容纳该组所有朋友的公交车的大小
pythonserver side programmingprogramming更新于 2025/5/1 7:40:17
假设有 n 个学生组等待乘坐校车从大学返回家中。每个学生组中有 m 名学生。学生组希望乘坐公交车而不走散。当且仅当该组所有成员都能上车时,他们才能上车。此外,如果上一组人尚未上车或已到达目的地,则该组不会上车。如果我们已知团体数量和每组学生人数,我们必须确定公交车的大小,以便公交车可以运送所有团体,并且每次公交车从大学出发时车内都没有空位。
因此,如果输入为 groups 或 gr_no = [3, 4, 2, 2, 1, 4, 3, 5],则输出将为 [12, 24]。
如果公交车大小为 12,它可以在第一次行程中容纳 1 - 5 组,在第二次行程中容纳其余组。
如果公交车大小为 24,它可以容纳所有团体并仅在一次行程中运送他们。
为了解决这个问题,我们将遵循以下步骤 −
- 定义一个函数 factor_ret() 。这将需要 n
- 对于 i 在范围内 (0 到 n ^ 0.5),执行
- 如果 n mod i 与 0 相同,则
- 将一个元组 (i,(n/i) 的底值) 添加到 output_list
- 如果 n mod i 与 0 相同,则
- 对列表 output_list 进行排序
- 将 output_list 作为集合返回
- 对于 i 在范围内 (0 到 n ^ 0.5),执行
- 现在执行以下步骤 −
- total := 一个包含项 gr_no[0] 的新列表
- 对于范围从 1 到 gr_no 大小的 i,执行
- 在 total 的末尾插入 total[i - 1] + gr_no[i]
- b_sizes := 一个新列表
- 对于 factor_ret(列表总和 (gr_no)) 中的每个大小,执行
- temp_list := 一个来自 total 的所有非零元素的新列表
- index := 1
- indicator := True
- 对于 temp_list 中的每个点,执行
- 如果点与大小 * 索引不相同,则
- indicator := False
- 退出循环
- index := index + 1
- 如果点与大小 * 索引不相同,则
- 如果指示符为 True,则
- 在 b_sizes 末尾插入大小
- return b_sizes
示例
让我们看看下面的实现以便更好地理解 −
from functools import reduce def solve(gr_no): total = [gr_no[0]] for i in range(1, len(gr_no)): total.append(total[i - 1] + gr_no[i]) b_sizes = [] for size in factor_ret(sum(gr_no)): temp_list = list(filter(lambda x : x % size == 0, total)) index = 1 indicator = True for point in temp_list: if point != size * index: indicator = False break index += 1 if indicator: b_sizes.append(size) return b_sizes def factor_ret(n): return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))) print(solve([3, 4, 2, 2, 1, 4, 3, 5]))
输入
[3, 4, 2, 2, 1, 4, 3, 5]
输出
[12, 24]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

