【发布时间】: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 哦,真的吗?我必须对我的代码进行哪些更改才能使其正常工作??