简体   繁体   中英

How to debug this recursion function python

I am working on this question from school, and I wrote the function I thought was the right one (we need to use recursion with no loops)

def subset_sum(numbers, target):
    '''
    numbers - a list of positive integers
    target - a non-negative integer
    returns True if the list 'numbers' has a sub-list with sum 'target',
            False otherwise.
    '''
    # Your code for question #4 starts here
    if sum(numbers[1:]) == target or target == 0:
        return True
    if sum(numbers[1:]) == (target - numbers[0]):
        return True
    if len(numbers) == 1 and numbers[0] == target:
        return True
    if len(numbers) == 1 and numbers[0] != target:
        return False
    else:
        subset_sum(numbers[1:], target)

For some inputs get the right output like subset_sum([4,4,4], 12) or subset_sum([4,4,4], 8) but for subset_sum([4,4,4], 4) I get no output.

Can someone take a look and tell me what's wrong here? When it doesn't give any output there are no errors, just blank.

You have to return the result of subset_sum in the else branch:

else:
    return subset_sum(numbers[1:], target)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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