在列表中查找总和为目标数字的一对数字

凯西遗嘱

我正在处理的任务指定编写一个名为的函数sum_pairs该函数接受一个列表和一个数字,并返回与传递的数字相加的第一对数字。

这是欲望的结果:

sum_pairs([4,2,10,5,1], 6) # [4,2]

我能想到的唯一方法是使用随机模块:

def sum_pairs(lst, num):
    rand_num_one = choice(lst)
    rand_num_two = choice(lst)
    if rand_num_one + rand_num_two == num:
        x = [rand_num_one, rand_num_two]
        return x

但是,我知道还有另一种方法可以做到这一点而不必使用随机模块。我只是不能把我的手指放在它上面。任何见解将不胜感激。

雷兹尼克

你为什么用random你需要返回第一笔款项

def sum_pairs(lst, num):
    for i in range(len(lst)):
        for j in range(i+1, len(lst)):
            if lst[i] + lst[j] == num:
                return lst[i],lst[j]

更新

如果你想使用这个random模块,你可以这样做:

def sum_pairs(lst, num):
    first = choice(lst)
    temp = lst[::]
    temp.remove(first)
    second = choice(temp)
    while first + second != num:
        first = choice(lst)
        temp = lst[::]
        temp.remove(first)
        second = choice(temp)
    return first,second

但这并不是你问题的真正答案

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章