【问题标题】:How can I find whether each element in a list can be added based on the given values or not?如何确定是否可以根据给定值添加列表中的每个元素?
【发布时间】:2022-01-16 06:19:27
【问题描述】:

所以我有一个函数findsum(s,g),我想知道s:list 中的元素是否可以是g: list 中任何数字的总和......例如,如果

s = [0,2,3,4,5]
g = [1,2,3],

输出应该返回

[False, True, True, True, True]

Explaination:
So 0 is false because nothing in g equals to or adds up to 0
2 is true because g contains a 2
3 is true because 2 and 1 in g adds up to 3
4 is true because if we add 2 to itself, 4 is the result
5 is also true because if we add 2 and 3 from g, we get 5

我尝试过的:

def findsum(s,g): 
       for f in g:         
           for x in s:            
               if sum (x) == f:               
                  return True            
               else:                         
                  return False 

我应该对我的代码进行哪些更改才能使其正常工作?

【问题讨论】:

  • 每个列表有多少个元素,取值范围是多少?因为如果 g 仅包含从 1 到 10 的值,而 f 仅包含大约 20 个从 1 到 200 的值,那么它与 fi 不同,您可以在 f 和 j 中包含任何整数,在 f 中包含 1000k 个不同的值?
  • 你明白你的代码现在根本不这样做吗?因为x 是一个整数,所以sum(x) == x,所以你只需检查是否相等,如果一旦它们不相等,则直接结束程序
  • 是的,列表中的元素数量没有限制。真正重要的是如果 g 中的元素相加或等于 s 中的元素,那么该元素的输出为 True在列表中
  • @azro 哦,真的吗?我必须对我的代码进行哪些更改才能使其正常工作??

标签: python list function sum


【解决方案1】:

使用itertools.combinations_with_replacement 生成给定值的所有组合(添加循环以生成所有尺寸)

list(combinations_with_replacement([1, 2, 3], r=3))
[(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3), (2, 2, 2), (2, 2, 3), (2, 3, 3), (3, 3, 3)]

然后检查总和,你return Falseonly在最后,测试所有组合后

from itertools import combinations_with_replacement    

def does_sum(values, target):
    for size in range(len(values)):
        for combi in combinations_with_replacement(values, r=size + 1):
            if sum(combi) == target:
                return True
    return False
    
def does_sum_multiple(values, targets):
    return [does_sum(values, target) for target in targets]

请注意,如果1 在值中,则所有结果都将为True

res = does_sum_multiple([1, 2, 3], [0, 2, 3, 4, 5])
print(res)  # [False, True, True, True, True]

res = does_sum_multiple([2, 6], [0, 2, 3, 4, 5])
print(res)  # [False, True, False, True, False]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    相关资源
    最近更新 更多