[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
相关推荐
牛奔3 小时前
Go 如何避免频繁抢占?
开发语言·后端·golang
寻星探路7 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
lly2024069 小时前
Bootstrap 警告框
开发语言
2601_949146539 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧9 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX9 小时前
服务异步通信
开发语言·后端·微服务·ruby
zmzb010310 小时前
C++课后习题训练记录Day98
开发语言·c++
ValhallaCoder10 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
猫头虎10 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
YUJIANYUE11 小时前
PHP纹路验证码
开发语言·php