[Python] Recursive function that finds pairs of numbers with opposite signs (python)

Discussão em 'Python' iniciado por Stack, Fevereiro 8, 2025.

  1. Stack

    Stack Membro Participativo

    In preparation for an exam in python I came across the following question:

    Write a recursive function "minus_plus" that receives a list containing non-zero integers. The function should return "True" if the length of the list is even, and for every element in the list there exists a matching pair (for example if 5 is in the list, so as (-5)). In any other case, the function will return False.

    For example:

    • minus_plus([-5,-7,2,5,-2,7]) = True
    • minus_plus([5,-5,3,5]) = False (-3 is not in the list)
    • minus_plus([5,-5,5]) = False (length of the list is odd)

    We are not allowed to use extra lists (create additional lists inside the function), nor are we allowed to modify the given list.

    We are allowed to use "helping" recursive functions, and parameter overloading (I am not sure what that means), nor are we allowed to use the "in" operator.

    Here is the beginning of the code I wrote, I couldn't complete the recursion:

    def minus_plus(lst):
    if len(lst) <= 1:
    return False
    elif len(lst)%2 != 0: #This deals with lst with len(lst)%2==1
    return False
    elif len(lst)==2: #The "optimal" case, possibly the base case for the recursion
    return lst[0]==(-1)*lst[1]

    Continue reading...

Compartilhe esta Página