2020年12月19日星期六

Python:memoization for cansum not storing any output

i am following a dynamic programming video. However the memoization for my code is not working. It is not storing any True/False when i print(memo) it is blank. Please advise

def cansum(targetsum,numbers):        memo = dict()        print(memo)        # check in memory        if targetsum in memo:              return memo[targetsum]        if targetsum < 0: return False        if targetsum == 0: return True        for number in numbers:              remainder = targetsum - number              if cansum(remainder,numbers) == True:                    memo[targetsum] = True                    return True        memo[targetsum] = False        return False      print(cansum(7,[2,3])) #True  print(cansum(7,[5,3,4,7])) #True  


from Recent Questions - Stack Overflow https://stackoverflow.com/questions/65376914/pythonmemoization-for-cansum-not-storing-any-output joseph gan

没有评论:

发表评论