【问题标题】:How to make python halt once target product is found in subset?一旦在子集中找到目标产品,如何使 python 停止?
【发布时间】: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


    【解决方案1】:

    将 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。

    【讨论】:

      猜你喜欢
      • 2021-01-18
      • 1970-01-01
      • 2016-02-25
      • 2019-12-10
      • 2016-11-01
      • 1970-01-01
      • 2021-04-09
      • 2018-01-24
      • 1970-01-01
      相关资源
      最近更新 更多