在 Python 中,可以使用给定的条件完成查找任务数量的程序
pythonserver side programmingprogramming更新于 2026/1/8 12:28:17
假设我们有一个任务列表和另一个人员列表。tasks[i] 确定执行第 i 个任务所需的力量。people[i] 确定第 i 个人的力量。最后,我们必须找出如果一个人最多可以执行一项任务,那么可以完成的任务数。
因此,如果输入为任务 = [4, 3, 9, 15],人员 = [10, 5, 3, 2],则输出将为 3,因为第一个人可以执行任务 9,第二个人可以执行任务 4,第三个人可以执行任务 3,第四个人不能执行任何任务。
为了解决这个问题,我们将遵循以下步骤 −
- 对任务列表进行排序,对人员列表进行排序
- ct:= 0, ind:= 0
- 对于 i 在 0 到人员大小的范围内,执行
- 对于 j 在 ind 到任务大小的范围内,执行
- 如果人员[i] >= 任务[j],然后
- ct := ct + 1
- ind := ind + 1
- 退出循环
- 否则,
- 退出循环
- 如果人员[i] >= 任务[j],然后
- 对于 j 在 ind 到任务大小的范围内,执行
- 返回 ct
让我们看看下面的实现以便更好地理解 −
示例
class Solution: def solve(self, tasks, people): tasks.sort() people.sort() ct=0 ind=0 for i in range(len(people)): for j in range(ind,len(tasks)): if people[i]>=tasks[j]: ct+=1 ind+=1 break else: break return ct ob = Solution() tasks = [4, 3, 9, 15] people = [10, 5, 3, 2] print(ob.solve(tasks, people))
输入
[4, 3, 9, 15], [10, 5, 3, 2]
输出
3
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

