Search code examples
pythonfunctionrecursionnonetype

Why is this list becoming NoneType when a recursion happens?


so im trying to make this code which finds if there is a subset of numbers in a list which sum up to a result which is also passed in. Whenever I run my code however for some reason my currentlist variable becomes NoneType. This is the error I get:

AttributeError: 'NoneType' object has no attribute 'append' 

This is my code:

def resultinSubset(t,s):
    currentlist=[]
    currentsum=0
    def recresultinSubset(t,s,i,currentsum,currentlist):
        if currentsum == t:
            return True
        if i == (len(s)):
            return False
        newlist=currentlist.append(s[i])
        newsum=int(currentsum)+int(s[i])
        including=recresultinSubset(t,s,i+1,newsum,newlist)
        notincl=recresultinSubset(t,s,i+1,currentsum,currentlist)
        return including + notincl
    return recresultinSubset(t,s,0,currentsum,currentlist)
    print(currentlist)                                  
print(resultinSubset(6, [1,2,3])) 

Solution

  • newlist=currentlist.append(s[i])
    

    This sets newlist = None since append() doesn't have a return value. If you want a new list with an extra value appended use:

    newlist = currentlist + [s[i]]
    

    Note that creating a new list every recursive call is quite inefficient. It'd be worth modifying the algorithm to manipulate a single list in place.