【发布时间】:2019-11-19 02:14:56
【问题描述】:
我一直在学习 Python,因为我的爱好和对 NP 完全问题(例如子集积)的实证研究。我的算法有效,但并没有按照我打算的方式进行。
我要做的是在 itertools'combinations 到达输入变量target 的子集产品时停止它。这将稍微使代码更快。代码在打磨阶段所以有一个不必要的列表res_2
这是循环。
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---any-length) 也是如此。我希望脚本继续运行直到它能够找到命中。一旦找到命中,它就会停止,因为这会提高算法的速度。
完整脚本如下
# 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技巧可以解决我的问题?有没有更短的方法?
【问题讨论】:
标签: python subset subset-sum