我一直在学习python,这是我对NP完全问题(例如子集产品)的爱好和经验研究。我有算法,但是并没有按照我打算的方式进行。
我想做的是一旦itertools到达输入变量combinations
的子集,就停止它。这会稍微加快代码的速度。该代码处于抛光阶段,因此没有必要的列表target
这是循环。
res_2 = [];
for i in range(1, len(s)+1):
var = (findsubsets(s, i))
kk = list(map(numpy.prod, var))
res_2.append(kk)
if target in kk:
print('yes')
print(var)
break
这是我不需要的输出。请注意,脚本不会在(4,4)处停止。一旦目标被“击中”,继续检查所有组合是浪费资源。
Enter numbers WITH SPACES: 4 4 3 12
enter target integer:
16
yes
[(4, 4), (4, 3), (4, 12), (4, 3), (4, 12), (3, 12)]
kk
[16, 12, 48, 12, 48, 36]
我的预期输出是在第一个“命中”处停止在(4,4)。对于其他任何子集,例如(1,2,3)或(1,2,3 ---任意长度),也是如此。我希望脚本继续执行直到找到匹配为止。一旦找到命中,它将停止,因为这将提高算法的速度。
完整脚本如下
# Naive Subset-Product solver
# with python's itertools
import itertools
import numpy
s = list(map(int, input('Enter numbers WITH SPACES: ').split(' ')))
print('enter target integer: ')
target = int(input())
if s.count(target) > 0:
print('yes')
quit()
if target > numpy.prod(s):
print('sorry cant be bigger than total product of s')
quit()
def findsubsets(s, n):
return list(itertools.combinations(s, n))
# Driver Code
n = len(s)
# This code snippet is a for loop. It also is intended to cut down execution
# time once it finds the target integer. (instead of creating all combinations)
res_2 = [];
for i in range(1, len(s)+1):
var = (findsubsets(s, i))
kk = list(map(numpy.prod, var))
res_2.append(kk)
if target in kk:
print('yes')
print(var)
break
题
如何使它起作用以提高算法速度?哪些pythonic技巧可以解决我的问题?有更短的方法吗?
参考方案
将itertools的combinations
返回值转换为list
还为时过早,尤其是当您尝试提早退出并避免过多开销时。通常有充分的理由使库函数返回迭代器而不是完全实现的列表。
这是一个建议:
def findsubsets(s, n):
return itertools.combinations(s, n)
def find_subset(target,nums):
for i in range(1,len(nums)+1):
for ss in findsubsets(nums, i):
if np.prod(ss) == target:
prodstr = '*'.join(str(num) for num in ss)
print(f"{target} = {prodstr}")
return ss
return None
find_subset(96,[1,6,2,8])
鉴于findsubsets
是单行,将其作为独立功能有点疑问(我们基本上只是为combinations
加上别名,而这可以用import X as Y
语句完成)。无论如何,这应该尽早停止,而不要在较大的输入上占用过多的RAM。
我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…
Python exchangelib在子文件夹中读取邮件 - python我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…
R'relaimpo'软件包的Python端口 - python我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。
Python ThreadPoolExecutor抑制异常 - pythonfrom concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…
Python GPU资源利用 - python我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…