0

I am working on the Dynamic programming concept using Python. I have designed a simple code that for for each recursion it divides the given input (n) by 2 and add in the memo dict. I want the memo dict as the return form this function.

n = 16

def myfunc(n, memo={}):

  if n in memo : return memo[n]
  if n == 0 : return 0
  if n == 1 : return 1
  if n % 2 == 0:
      memo[n] = myfunc(n // 2)
  else:
      pass
  return memo   

res = myfunc(n)
print(res) 

But when i am executing this above code i am getting this as the result :

{2: 1, 4: {...}, 8: {...}, 16: {...}}

I don't understand where this {...} is coming from ??

I want the result {2: 1, 4: 1, 8: 1, 16: 1} , logically.

1
  • 1
    this {...} is python's print function safeguard against endless printing - in this case it means {...} is the dict you're printing, which makes sense since you have code that inserts the returning value from your function to it and you're also returning that very dict. overall it would be better to say what you want this function to do because currently your code is broken in many different ways and it's hard to suggest a full solution without it. Jun 16, 2022 at 9:42

1 Answer 1

0

The problem is, that you are returning the same memo object all the time. Try something like this:

def myfunc(n, memo={}):
    if n <= 1: return
    if n % 2 == 0:
        memo[n] = 1

    myfunc(n // 2, memo)

    return memo


res = myfunc(16)
print(res)

1
  • 1
    Thanks , it works.. i saw the error while debugging .. ! How ever i was just not able to understand this { ... } dict returned from this function Jun 16, 2022 at 9:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.