- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我是 Python 的新手,我正在通过 Codewars 慢慢学习。我知道这可能违反规则,但我有一个效率问题。
给你一个整数列表
ls = [100, 76, 56, 44, 89, 73, 68, 56, 64, 123, 2333, 144, 50, 132, 123, 34, 89]
你必须写一个函数 choose_best_sum(t, k, ls)
这样你就可以从 ls 中找到 k 个整数的组合,使得这 k 个整数的总和接近或等于 t。
我的最终解决方案通过了测试,但在更详细的测试中失败了,这可能是因为效率问题。我想更多地了解效率。这是我的代码
import itertools
def choose_best_sum(t, k, ls):
if sum(sorted(ls)[:k]) > t or len(ls) < k:
return None
else:
combos = itertools.permutations(ls, k)
return max([[sum(i)] for i in set(combos) if sum(i) <= t])[0]
有人可以强调这里的瓶颈在哪里(我假设在排列调用中)以及如何使这个函数更快?
编辑:
上面的解决方案给出了剖析
在 0.458 秒内调用了 1806730 次函数
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.457 0.457 <string>:1(<module>)
1 0.000 0.000 0.457 0.457 exercises.py:14(choose_best_sum)
742561 0.174 0.000 0.305 0.000 exercises.py:19(<genexpr>)
321601 0.121 0.000 0.425 0.000 exercises.py:20(<genexpr>)
1 0.000 0.000 0.458 0.458 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {built-in method builtins.len}
1 0.032 0.032 0.457 0.457 {built-in method builtins.max}
1 0.000 0.000 0.000 0.000 {built-in method builtins.sorted}
742561 0.131 0.000 0.131 0.000 {built-in method builtins.sum}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
借助帮助,我得到的最终解决方案是:
def choose_best_sum(t, k, ls):
ls = [i for i in ls if i < t and i < (t - sum(sorted(ls)[:k-1]))]
if sum(sorted(ls)[:k]) > t or len(ls) < k:
return None
else:
return max(s for s in (sum(i) for i in itertools.combinations(ls, k)) if s <= t)
排序依据:标准名称
在 0.002 秒内调用了 7090 个函数
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.003 0.003 <string>:1(<module>)
2681 0.001 0.000 0.003 0.000 exercises.py:10(<genexpr>)
1 0.000 0.000 0.003 0.003 exercises.py:5(choose_best_sum)
1 0.000 0.000 0.000 0.000 exercises.py:6(<listcomp>)
1 0.000 0.000 0.003 0.003 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {built-in method builtins.len}
1 0.000 0.000 0.003 0.003 {built-in method builtins.max}
17 0.000 0.000 0.000 0.000 {built-in method builtins.sorted}
4385 0.001 0.000 0.001 0.000 {built-in method builtins.sum}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
最佳答案
你的表达有几个明显的缺陷
max([[sum(i)] for i in set(combos) if sum(i) <= t])[0]
您无缘无故地运行了两次 sum(i)
;
您正在将结果打包到列表中 ([sum(i)]
),然后将其解包 ([0]
)
您无缘无故地将 combos
转换为集合
尝试将其替换为
sums = [sum(c) for c in combos]
return max(s for s in sums if s <= t)
编辑:好的,关于更好算法的一些想法:
噢!首先,使用 itertools.combinations
而不是 itertools.permutations
。你只是在取总和;项目的顺序没有区别。如果您在 ie k = 4 上运行,combinations
将返回 4! == 与相同输入数据的排列
相比条目少 24 倍。
其次,我们希望在一开始就从 ls
中丢弃尽可能多的项目。显然我们可以丢弃任何 > t 的值;但我们可以得到比这更严格的界限。如果我们添加 (k - 1) 个最小值,则最大允许值必须是 <= t - (k-1)_sum。
(如果我们正在寻找一个精确的总和,我们可以反向运行这个技巧 - 将 (k - 1) 个最大值相加会给我们一个最小允许值 - 我们可以重复应用这两个规则来丢弃更多可能性.但这并不适用于此。)
第三,我们可以查看 (k - 1) 个值的所有组合,然后使用 bisect.bisect_left
直接跳转到最佳可能的第 k 个值。有一点复杂,因为您必须仔细检查第 k 个值是否尚未被选为 (k - 1) 值之一 - 您不能直接使用内置 itertools.combinations
函数,但您可以使用 itertools.combinations code 的修改副本(即测试 bisect_left
返回的索引高于当前使用的最后一个索引)。
这些应该一起加速你的代码 len(ls) * k * k!
...祝你好运!
编辑 2:
让这成为过度优化危险的教训:-)
from bisect import bisect_right
def choose_best_sum(t, k, ls):
"""
Find the highest sum of `k` values from `ls` such that sum <= `t`
"""
# enough values passed?
n = len(ls)
if n < k:
return None
# remove unusable values from consideration
ls = sorted(ls)
max_valid_value = t - sum(ls[:k - 1])
first_invalid_index = bisect_right(ls, max_valid_value)
if first_invalid_index < n:
ls = ls[:first_invalid_index]
# enough valid values remaining?
n = first_invalid_index # == len(ls)
if n < k:
return None
# can we still exceed t?
highest_sum = sum(ls[-k:])
if highest_sum <= t:
return highest_sum
# we have reduced the problem as much as possible
# and have not found a trivial solution;
# we will now brute-force search combinations of (k - 1) values
# and binary-search for the best kth value
best_found = 0
# n = len(ls) # already set above
r = k - 1
# itertools.combinations code copied from
# https://docs.python.org/3/library/itertools.html#itertools.combinations
indices = list(range(r))
# Inserted code - evaluate instead of yielding combo
prefix_sum = sum(ls[i] for i in indices) #
kth_index = bisect_right(ls, t - prefix_sum) - 1 # location of largest possible kth value
if kth_index > indices[-1]: # valid with rest of combination?
total = prefix_sum + ls[kth_index] #
if total > best_found: #
if total == t: #
return t #
else: #
best_found = total #
x = n - r - 1 # set back by one to leave room for the kth item
while True:
for i in reversed(range(r)):
if indices[i] != i + x:
break
else:
return
indices[i] += 1
for j in range(i+1, r):
indices[j] = indices[j-1] + 1
# Inserted code - evaluate instead of yielding combo
prefix_sum = sum(ls[i] for i in indices) #
kth_index = bisect_right(ls, t - prefix_sum) - 1 # location of largest possible kth value
if kth_index > indices[-1]: # valid with rest of combination?
total = prefix_sum + ls[kth_index] #
if total > best_found: #
if total == t: #
return t #
else: #
best_found = total #
else:
# short-circuit! skip ahead to next level of combinations
indices[r - 1] = n - 2
# highest sum found is < t
return best_found
关于Python:如何让这段代码运行得更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44572683/
我尝试理解[c代码 -> 汇编]代码 void node::Check( data & _data1, vector& _data2) { -> push ebp -> mov ebp,esp ->
我需要在当前表单(代码)的上下文中运行文本文件中的代码。其中一项要求是让代码创建新控件并将其添加到当前窗体。 例如,在Form1.cs中: using System.Windows.Forms; ..
我有此 C++ 代码并将其转换为 C# (.net Framework 4) 代码。有没有人给我一些关于 malloc、free 和 sprintf 方法的提示? int monate = ee; d
我的网络服务器代码有问题 #include #include #include #include #include #include #include int
给定以下 html 代码,将列表中的第三个元素(即“美丽”一词)以斜体显示的 CSS 代码是什么?当然,我可以给这个元素一个 id 或一个 class,但 html 代码必须保持不变。谢谢
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 7 年前。
我试图制作一个宏来避免重复代码和注释。 我试过这个: #define GrowOnPage(any Page, any Component) Component.Width := Page.Surfa
我正在尝试将我的旧 C++ 代码“翻译”成头条新闻所暗示的 C# 代码。问题是我是 C# 中的新手,并不是所有的东西都像 C++ 中那样。在 C++ 中这些解决方案运行良好,但在 C# 中只是不能。我
在 Windows 10 上工作,R 语言的格式化程序似乎没有在 Visual Studio Code 中完成它的工作。我试过R support for Visual Studio Code和 R-T
我正在处理一些报告(计数),我必须获取不同参数的计数。非常简单但乏味。 一个参数的示例查询: qCountsEmployee = ( "select count(*) from %s wher
最近几天我尝试从 d00m 调试网络错误。我开始用尽想法/线索,我希望其他 SO 用户拥有可能有用的宝贵经验。我希望能够提供所有相关信息,但我个人无法控制服务器环境。 整个事情始于用户注意到我们应用程
我有一个 app.js 文件,其中包含如下 dojo amd 模式代码: require(["dojo/dom", ..], function(dom){ dom.byId('someId').i
我对“-gencode”语句中的“code=sm_X”选项有点困惑。 一个例子:NVCC 编译器选项有什么作用 -gencode arch=compute_13,code=sm_13 嵌入库中? 只有
我为我的表格使用 X-editable 框架。 但是我有一些问题。 $(document).ready(function() { $('.access').editable({
我一直在通过本教程学习 flask/python http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-wo
我想将 Vim 和 EMACS 用于 CNC、G 代码和 M 代码。 Vim 或 EMACS 是否有任何语法或模式来处理这种类型的代码? 最佳答案 一些快速搜索使我找到了 this vim 和 thi
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 想改进这个问题?更新问题,使其成为 on-topic对于堆栈溢出。 7年前关闭。 Improve this
这个问题在这里已经有了答案: Enabling markdown highlighting in Vim (5 个回答) 6年前关闭。 当我在 Vim 中编辑包含 Markdown 代码的 READM
我正在 Swift3 iOS 中开发视频应用程序。基本上我必须将视频 Assets 和音频与淡入淡出效果合并为一个并将其保存到 iPhone 画廊。为此,我使用以下方法: private func d
pipeline { agent any stages { stage('Build') { steps { e
我是一名优秀的程序员,十分优秀!