发现总结于给定号码的所有可能子集

编程入门 行业动态 更新时间:2024-10-10 11:21:10
本文介绍了发现总结于给定号码的所有可能子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在学习Python和我有一个问题,这个看似简单的任务。

I'm learning Python and I have a problem with this seems to be simple task.

欲查找相加为一个给定数目的数字的所有可能的组合。 例如:4 - > [1,1,1,1] [1,1,2] [2,2] [1,3]

I want to find all possible combination of numbers that sum up to a given number. for example: 4 -> [1,1,1,1] [1,1,2] [2,2] [1,3]

我挑选哪些生成所有可能子集(2 ^ n)和然后将溶液收率只是那些总和等于数。我的条件的问题。 code:

I pick the solution which generate all possible subsets (2^n) and then yield just those that sum is equal to the number. I have a problem with the condition. Code:

def allSum(number): #mask = [0] * number for i in xrange(2**number): subSet = [] for j in xrange(number): #if : subSet.append(j) if sum(subSet) == number: yield subSet for i in allSum(4): print i

BTW是一个不错的方法?

BTW is it a good approach?

推荐答案

下面是一些code我看到了几年前做的伎俩:

Here's some code I saw a few years ago that does the trick:

>>> def partitions(n): if n: for subpart in partitions(n-1): yield [1] + subpart if subpart and (len(subpart) < 2 or subpart[1] > subpart[0]): yield [subpart[0] + 1] + subpart[1:] else: yield [] >>> print list(partitions(4)) [[1, 1, 1, 1], [1, 1, 2], [2, 2], [1, 3], [4]]

其他参考:

  • mathworld.wolfram/Partition.html
  • en.wikipedia/wiki/Partition_(number_theory )
  • www.site.uottawa.ca/~伊万/ F49-INT-part.pdf
  • mathworld.wolfram/Partition.html
  • en.wikipedia/wiki/Partition_(number_theory)
  • www.site.uottawa.ca/~ivan/F49-int-part.pdf

更多推荐

发现总结于给定号码的所有可能子集

本文发布于:2023-11-30 06:54:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649089.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子集   号码   发现

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!