Python子集总和 [英] Python Subset Sum
本文介绍了Python子集总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个函数,该函数不仅可以确定集合子集的总和是否与所需的目标数相加,而且还可以打印作为解决方案的子集.
I am trying to write a function that will not only determine whether the sum of a subset of a set adds to a desired target number, but also to print the subset that is the solution.
这是我查找子集是否存在的代码:
Here is my code for finding whether a subset exists:
def subsetsum(array,num):
if num == 0 or num < 1:
return False
elif len(array) == 0:
return False
else:
if array[0] == num:
return True
else:
return subsetsum(array[1:],(num - array[0])) or subsetsum(array[1:],num)
如何修改它以记录子集本身以便我可以打印它?提前致谢!
How can I modify this to record the subset itself so that I can print it? Thanks in advance!
推荐答案
基于您的解决方案:
def subsetsum(array,num):
if num == 0 or num < 1:
return None
elif len(array) == 0:
return None
else:
if array[0] == num:
return [array[0]]
else:
with_v = subsetsum(array[1:],(num - array[0]))
if with_v:
return [array[0]] + with_v
else:
return subsetsum(array[1:],num)
这篇关于Python子集总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文