给定的数字列表,检查是否存在添加到100的数字。将所有这些数字列出为列表列表
Input : L=[1,50,16,34,8,42,99]
Output : [[50,8,42],[16,34,50],[99,1],[16,34,42,8]]
创建一个函数check_sum_100(l)
我能够找到当元素形成子阵列时总计100的元素的总和。但是我找不到[99,1]
之类的元素列表。
这是我尝试实现的方法:
def check_sum_100(L):
out=[]
for i in range(0, len(L)):
for j in range(i, len(L)):
sum = 0
temp = []
for k in range (i, j+1):
sum = sum + L[k]
temp.append(L[k])
if sum == 100:
out.append(temp)
return out
L = [1,50,16,34,8,42,99]
o = check_sum_100(L)
print(o)
Input : L=[1,50,16,34,8,42,99]
Output : [[50,8,42],[16,34,50],[99,1],[16,34,42,8]]
Create a function check_sum_100(L)
I am able to find the sum of elements that add up to 100 when the elements form sub-array. But I am not able to find list of elements like [99,1]
.
Here is what I tried to implement:
def check_sum_100(L):
out=[]
for i in range(0, len(L)):
for j in range(i, len(L)):
sum = 0
temp = []
for k in range (i, j+1):
sum = sum + L[k]
temp.append(L[k])
if sum == 100:
out.append(temp)
return out
L = [1,50,16,34,8,42,99]
o = check_sum_100(L)
print(o)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
itertools.combinations
获取不同长度的sublists并检查总和:Use
itertools.combinations
to get sublists of varying length and check for the sum:您可以将递归用于此类问题:
输出:
You can use recursion for this sort of problem:
Output: