[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
相关推荐
lang201509281 分钟前
深入解析Java资源加载机制
java·开发语言·python
爱笑的眼睛1135 分钟前
自动机器学习组件的深度解析:超越AutoML框架的底层架构
java·人工智能·python·ai
LCG米38 分钟前
嵌入式Python工业环境监测实战:MicroPython读取多传感器数据
开发语言·人工智能·python
自学小白菜40 分钟前
每周刷题 - 第三周 - 双指针专题 - 02
python·算法·leetcode
武汉唯众智创1 小时前
职业院校C语言程序设计(AIGC版)课程教学解决方案
c语言·开发语言·aigc·程序设计·c语言程序设计·c语言程序设计实训室
开发转测试1 小时前
python编码笔试题
python
祝余Eleanor1 小时前
Day37 模型可视化与推理
人工智能·python·深度学习
qq_401700411 小时前
C语言void*
c语言·开发语言
sg_knight1 小时前
Python 面向对象基础复习
开发语言·python·ai编程·面向对象·模型
dhdjjsjs2 小时前
Day35 PythonStudy
python