简体   繁体   English

Python递归列表对和

[英]Python Recursion List Sum of Pairs

I am supposed to write two functions that do the exact same thing but their implementation is different. 我应该写两个功能完全相同的东西,但是它们的实现不同。

The function takes as input a list of positive integers and a positive integer n, and returns True if two of the numbers in list equal to n. 该函数将一个正整数和一个正整数n的列表作为输入,如果列表中的两个数字等于n,则返回True。 Otherwise, it returns False. 否则,它返回False。

The first function is supposed to use a nested a loop, which I was able to get. 第一个功能应该使用嵌套的循环,我能够得到。

The second functions is not supposed to use a nested loop. 第二个函数不应使用嵌套循环。 However, you are supposed to sort the list out and then solve the problem. 但是,应该对列表进行排序,然后解决问题。

Here is what I have for the second function. 这是我对第二个功能的要求。

def pairs2(lst, n):
    lst.sort()
    if len(lst) == 2:
        if lst[0] + lst[1] == n:
            return True
        else:
            return False
    elif len(lst) >= 3:
        for i in range(len(lst) - 1):
            if lst[0] + lst[i + 1] == n:
                return True
        lst.remove(lst[0])
        pairs2(lst, n)

The function works until the last two lines are implemented. 该功能在实现最后两行之前一直有效。 After that, it doesn't return anything. 在那之后,它什么也不返回。 What is wrong with my function? 我的功能出了什么问题?

Also, are they any other alternatives to that I do not use recursion? 另外,它们还有其他不使用递归的替代方法吗? I just came up with using recursion since it was the first idea that I got. 我只是想使用递归,因为这是我的第一个想法。

A recursive algorithm that eliminates the largest number at each recursive step: 一种递归算法,可在每个递归步骤中消除最大数目:

def pairs2(lst, n, s=False): 
    if len(lst) < 2: return False
    if not s: lst = sorted(lst)
    for item in lst:
        if item + lst[-1] > n:  
            return pairs2(lst[:-1], n, True)
        if item + lst[-1] == n:
            print item, lst[-1]
            return True
    return False

The s parameter indicates whether the list is already sorted or not. s参数指示列表是否已排序。

def pairs2(lst, n):
   [pair for pair in itertools.combinations(lst,2) if sum(pair) == n]

Instead of using recursion, you could use the brute-force approach to find the pairs using the itertools.combinations. 除了使用递归之外,还可以使用蛮力方法通过itertools.combinations查找对。

Read more about itertools: https://docs.python.org/2/library/itertools.html 阅读有关itertools的更多信息: https ://docs.python.org/2/library/itertools.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM