一旦在子集中找到目标产品,如何让 python 停止?

How to make python halt once target product is found in subset?

我一直在学习 python 因为我的爱好和对 NP 完全问题(例如子集积)的实证研究。我的算法有效,但它没有按照我打算的方式进行。

我想要做的是在 itertools 到达输入变量 target 的子集乘积后停止它 combinations。这将使代码稍微更快。代码还在完善阶段,所以有一个不必要的列表 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) 处停止。一旦目标是 "hit."

,继续检查所有组合是一种资源浪费
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]

如果第一个 "hit." 我的预期输出是在 (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 return 值转换为 list 为时过早,尤其是当您试图提前退出并避免过多开销时。库函数 return 迭代器而不是完全实现的列表通常是有充分理由的。

这里有一个建议:

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 和更大的输入。