[Python] 贪心算法简单版

贪心算法-简单版

贪心算法的一般使用场景是给定一个列表ls, 让你在使用最少的数据的情况下达到或超过n .

我们就来使用上面讲到的这个朴素的例题来讲讲贪心算法的基本模板:

2-1.排序

既然要用最少的数据, 我们就要优先用大的数据拼 , 为了实现这个效果, 我们得先给列表从大到小排序.

python 复制代码
sorted(ls, reverse = True)
# 别忘了reverse = True从大到小

2-2.选择

我们需要遍历列表, 每次选出现在的元素, 记录当前总和和累加次数, 当总和大于等于n时, 结束循环.

python 复制代码
tot = 0
cnt = 0
# 注意一个很容易错的地方, 这里的语句顺序不可改变!
for l in ls:
	tot += l
	if tot >= n:
		break
	cnt += 1

2-3.完整简单版模板

注释版:

python 复制代码
# 输入
n = int(input())
ls = [int(i) for i in input().split()]

# 排序
sorted(ls, reverse = True)

# 主要算法, 摘大苹果
tot = 0
cnt = 0
for l in ls:
	tot += l
	if tot >= n:
		break
	cnt += 1

记忆版:

python 复制代码
n = int(input())
ls = [int(i) for i in input().split()]
sorted(ls, reverse = True)
tot = 0
cnt = 0
for l in ls:
	tot += l
	if tot >= n:
		break
	cnt += 1
相关推荐
吠品2 分钟前
处理 Python 类继承中那些变来变去的初始化参数
linux·前端·python
人道领域5 分钟前
【LeetCode刷题日记】90.子集Ⅱ--- 归纳题解
java·开发语言·leetcode
会Tk矩阵群控的小木5 分钟前
小红书矩阵软件:基于Python+ADB的多设备批量管理自动化脚本实战
运维·python·adb·矩阵·自动化·新媒体运营·个人开发
ch.ju11 分钟前
Java Programming Chapter 4——Characteristics of inheritance
java·开发语言
复园电子12 分钟前
企业PDF批量盖章开发集成指南:API对接OA/LIMS系统,高并发落地实战
开发语言·python·pdf
SunnyDays101117 分钟前
如何使用 C# 自动调整 Excel 行高和列宽
开发语言·c#·excel
石山代码20 分钟前
类型限定符的底层实现原理是什么?
python
雾沉川25 分钟前
PyCharm 2025.2 完整安装与配置技术教程
ide·python·pycharm
a诠释淡然29 分钟前
C++模板元编程—现代C++的黑魔法
开发语言·c++
眠りたいです31 分钟前
LangChainv1:agent快速上手与中间件认识
人工智能·python·中间件·langchain·langgraph