在整数列表中查找所有加起来为数字的数字 [英] Find all numbers in a integer list that add up to a number

查看:30
本文介绍了在整数列表中查找所有加起来为数字的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

面试中有人问我这个问题.给出以下列表:

I was asked this question on an interview. Given the following list:

[1,2,5,7,3,10,13]

找到加起来为5的数字.

Find the numbers that add up to 5.

我的解决方法如下:

#sort the list:
l.sort()
result = ()
for i in range(len(l)):
    for j in range(i, len(l)):
         if l[i] + l[j] > 5:
             break
         elif l[i] + l[j] == 5:
             result += (l[i], l[j])

我提出的想法是对列表进行排序,然后循环查看总和是否大于5.如果是,那么我可以停止循环.我感觉到面试官对这个答案不满意.有人可以提出更好的建议供我将来参考吗?

The idea I presented was to sort the list, then loop and see if the sum is greater than 5. If so, then I can stop the loop. I got the sense the interviewer was dissatisfied with this answer. Can someone suggest a better one for my future reference?

推荐答案

这将返回输入功率集的所有元素,这些元素的总和为5:

This will return all elements of the powerset of the input that sum up to 5:

>>> input = [1,2,5,7,3,10,13]
>>> import itertools
>>> def powerset(l):
...     return itertools.chain.from_iterable((itertools.combinations(l, i) for i in range(len(l)+1)))
...
>>> filter(lambda v: sum(v) == 5, powerset(input))
[(5,), (2, 3)]

这篇关于在整数列表中查找所有加起来为数字的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆