【问题标题】:Python: How to calculate combinations of parts of a given number, giving the number, list lenght, first and last numberPython:如何计算给定数字的部分组合,给出数字,列表长度,第一个和最后一个数字
【发布时间】:2016-12-19 05:24:13
【问题描述】:

我非常坚持这一点(可能是因为我是计算机编程新手)。 我有以下代码,来自问题:[Python: Find all possible combinations of parts of a given number

def sum_to_n(n, size, limit=None):
    """Produce all lists of `size` positive integers in decreasing order
    that add up to `n`."""
    if size == 1:
        yield [n]
        return
    if limit is None:
        limit = n
    start = (n + size - 1) // size
    stop = min(limit, n - size + 1) + 1
    for i in range(start, stop):
        for tail in sum_to_n(n - i, size - 1, i):
            yield [i] + tail

for partition in sum_to_n(8, 3):
    print (partition)

[6, 1, 1]
[5, 2, 1]
[4, 3, 1]
[4, 2, 2]
[3, 3, 2]

它是否非常有用,但我正在尝试对其进行修改以设置一些选项。假设我只想得到列表的第一个数字是 4 而列表的最后一个数字是 1 的结果。 目前我使用这个解决方案:

def sum_to_n(n,first, last, size, limit=None):
    if size == 1:
        yield [n]
        return
    if limit is None:
        limit = n
    start = (n + size - 1) // size
    stop = min(limit, n - size + 1) + 1
    for i in range(start, stop):
        if i <=first:
            for tail in sum_to_n(n - i,first,last, size - 1, i):
                ll=len(tail)
                if tail[ll-1]==last:
                    yield [i] + tail

for i in sum_to_n(8,4,1,3):
    if i[0]==4 and i[size-1]==1:
        print(i)
    if i[0]>4:
        break

[4,3,1]

但是对于较大的整数,程序会做很多不需要的工作。 例如,for i in range(start, stop): 计算列表中所有可能的第一个数字,而不仅是 nedded 的“first”参数,而且如果没有它,该函数将无法工作。 有人可以建议一个更好更快的解决方案来调用函数,提供所需的参数以便只进行请求的计算?

【问题讨论】:

  • 当我在 Python 3.5.2 中运行您的第一个代码时,我得到了相同的列表,但顺序相反。你真的得到了你显示的顺序吗?
  • 不,只是举例,不是实际输出

标签: python math combinatorics


【解决方案1】:

既然你知道第一个数字,你只需要解决最后一个的 if。

在您的示例中,这将给出如下内容:

for res in sum_to_n(n=8-4, last=1, size=3-1):
   print([4] + res)

【讨论】:

  • 是的,有趣且鼓舞人心。最后我找到了一种使用你的想法的方法。我从总和“n”中减去第一个和最后一个数字,并只为“中间”数字调用该函数。然后简单的加入三个部分:first、res、last。这种方式比较快。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 2022-01-05
  • 2018-03-18
  • 2020-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多