How to compare a return value of a recursive function with an integer (actual parameter of function)

1.9k Views Asked by At

I need to compare the return value of a recursive function with an integer. Doing recursively the sum of all elements of a list , I have to compare the final sum with an integer "n" giving back TRUE if sum == n , FALSE if sum != n . In addiction to the function have to return FALSE if i'm giving an empty list . Here I report the code to clarify the situation :)

def function(list_of_numbers,int):

   if not list:

     return false # I have to return false if list is empty.

   if len(l) > 0:

     return l[0] + function(list_of_numbers[1:],int) # recursive sum of element

   # and here i'm stuck !
1

There are 1 best solutions below

14
On BEST ANSWER

when not l we either got passed an empty list or have reached our base case so compare n to our test number, if you want an empty list to return True change test=-1 to test=0 :

def function(l, n=0, test=-1):
    if not l:
        return n == test
    else:
        n += l[0]
        return function(l[1:], n, test)


In [2]: function([1,2,3],test=6)
Out[2]: True

In [3]: function([1,2,3],test=5)
Out[3]: False

In [4]: function([1,2,3])
Out[4]: False

In [5]: function([])
Out[5]: False

If you want an empty list to return False you can check how many times the function has been called and either compare n to test or return False :

def function(l, n=0, test=0, calls=0):
    if not l:
        return n == test if calls > 0 else False
    else:
        n += l[0]
        calls += 1
        return function(l[1:], n, test,calls)

If you just want to pass a single argument the number to test against:

def function(l, test, n=0, calls=0):
    if not l and calls == 0: # changed for jython
        return False
    if not l:
        return n == test 
    else:
        n += l[0]
        calls += 1
        return function(l[1:],test,n, calls)