python - Finding shortest sublist with sum greater than 50
问题描述
I have a list and I want to find shortest sublist with sum greater than 50. For example my list is
[8.4 , 10.3 , 12.9 , 8.2 , 13.7 , 11.2 , 11.3 ,10.4 , 4.2 , 3.3 , 4.0 , 2.1]
and I want to find shortest sublist so that its sum is more than 50.
Output Should be like [12.9 , 13.7 , 11.2 , 11.3, 10.4]
解决方案
这是一个糟糕的解决方案(就不做所有图形搜索并找到最佳值而言),但解决方案是正确的
lis =[8.4 , 10.3 , 12.9 , 8.2 , 13.7 , 11.2 , 11.3 ,10.4 , 4.2 , 3.3 , 4.0 , 2.1]
from collections import defaultdict
dic = defaultdict(list)
for i in range(len(lis)):
dic[lis[i]]+=[i]
tmp_lis = lis.copy()
tmp_lis.sort(reverse=True)
res =[]
for i in tmp_lis:
if sum(res)>50 :
break
else:
res.append(i)
res1 = [(i,dic[i]) for i in res]
res1.sort(key=lambda x:x[1])
solution =[i[0] for i in res1]
输出
[12.9, 13.7, 11.2, 11.3, 10.4]
推荐阅读
- reactjs - 如何使用 React Query 在与 Flatlist 的本机反应中实现无限列表
- django - Docker 中的 VueJS + Django Rest 框架
- c - 我想将 cf[] 中的二进制转换为十进制,它是一个文本文件,所以二进制是一个非常大的二进制,我需要将它转换为十进制
- c# - .NET 5 FileNotFoundException .resources
- python - 读取配置文件以填充 conanfile.py 中的包名称
- shell - 检索 GCP 实例的总 RAM 量
- c - 8 位处理器的无符号值的最佳实践有符号算术
- javascript - nuxt.js - 构建缺少页面的 ssr
- xaml - 将按钮注入现有网格
- go - 如何将此 IDNA URL 转换为 Unicode?