【问题标题】:How can I sum number of a list我怎样才能总结一个列表的数量
【发布时间】:2020-03-30 10:24:30
【问题描述】:

我正在寻找如何创建一个包含 6 个数字的列表。 我有一个我研究的数字,比如 30,它是我列表中的数字相加的结果

这里是一个简单的例子:

list=[]
list.append[1,5,5,10,8,2]

and the number that I want in rapport with the list is for example 30

所以解决方案是 5+5+10+8+2=30

它返回给我 30 个不同的步骤

当然你有一个约束。这是您不能使用相同的数字 2 次,但您可以存储一个结果以供以后使用。

目前我只有一个函数可以返回不同的列表添加但我无法将结果与下一个数字相加..

所以我的问题是,我如何创建一个函数来尝试所有添加的可能性以及我要获得的列表的数量,例如这里 30,

例如,我想以上面的列表为例:

1+5=6 # 30 so I continue, 6+5#11 so I continue ...  And at the end I need find the right way to find 30

所以这里的解决方案是:

5+5=10
10+10=20
20+8=28
28+2=30   and 30 is my research number so we stop the function and we print the steps to have the good solution.

谢谢!

【问题讨论】:

  • 你的问题是什么?
  • 我更改我的帖子以更清楚地解释我的问题
  • 您是在问:如何从列表中获取所有可能的数字组合并将每个组合相加?
  • 是的,我的列表中所有可能的组合,但我想要一个特定的约束。我编辑我的帖子向您展示更多内容
  • 恐怕你的问题非常不清楚。我不明白你在问什么。也许其他人可以帮助你。

标签: python list function


【解决方案1】:

我认为这是一个经典问题(我不记得名字了),我为你写了一个简单的基于回溯的解决方案。应该有更好的(性能方面)解决方案。

您可以将答案放在全局列表中,或者通过一些工作将其返回,而不是打印。

def sub(all_numbers: list, current_index: int, goal: int) -> bool:
    """
    Tries to construct goal using all_numbers[current_index:] if the goal can be reached it will print picked numbers
    and return True
    """
    if current_index >= len(all_numbers):
        return goal == 0
    if goal < 0:
        return False
    current = all_numbers[current_index]
    pick_current_result = sub(all_numbers, current_index + 1, goal - current)
    if pick_current_result:
        print(current)
        return True
    dont_pick_current_result = sub(all_numbers, current_index + 1, goal)
    return dont_pick_current_result


def solve(all_numbers: list, goal: int):
    sub(all_numbers, 0, goal)


solve([1, 5, 5, 10, 8, 2], 30)

【讨论】:

  • @raph 目标是您尝试查找总和的数字。这里一开始是30。在下一步中,我们假设取 1 并在列表的其余部分 ([5, 5, 10, 8, 2]) 中搜索 29。
【解决方案2】:

这是一种使用递归生成器函数的方法:

def sumto(n, lst):
    if not n and not lst:  # base case 1: empty list = 0
        yield []
        return
    if n < 0 or not lst:  # base case 2: unsolvable
        return
    head, *tail = lst
    for sol in sumto(n-head, tail):  # recursion 1: use first element
        yield [head] + sol
    yield from sumto(n, tail)  # recursion 2: don't use first element

>>> list(sumto(30, [1,5,5,10,8,2]))
[[5, 5, 10, 8, 2]]
>>> list(sumto(28, [1,5,5,10,8,2]))
[[5, 5, 10, 8]]
>>> list(sumto(42, [1,5,5,10,8,2]))
[]
>>> list(sumto(10, [1,5,5,10,8,2]))
[[5, 5], [10], [8, 2]]

【讨论】:

  • *tail 是什么意思?
  • tail == lst[1:]。符号a, *b = c 解包可迭代的c,将其第一个元素分配给a,并将其余元素打包到列表b
  • 所以你以第一个元素为例,你用列表中的所有其他元素计算第一个元素?
  • @raph 你可以,最好在一条评论中。我可以在帖子中添加解释。
  • 你看到我的问题了吗?
猜你喜欢
  • 2022-07-06
  • 2011-07-11
  • 2021-02-26
  • 2022-10-04
  • 2022-09-24
  • 1970-01-01
  • 2019-10-30
  • 2023-02-05
  • 1970-01-01
相关资源
最近更新 更多