- Move
d = dict()to after the argument checks, so that you only create the dictionary if the inputs are validMove
d = dict()to after the argument checks, so that you only create the dictionary if the inputs are valid. The
if/elsestatements inside theforloop can be removed:for i in range(1, lim+1): n = num - i if n: dic.setdefault(i, dict()) worker(n, lim, dic[i]) else: dic.update({i: 0}) breakbecomes:
for i in range(1, min(num, lim+1)): n = num - i dic.setdefault(i, dict()) worker(n, lim, dic[i]) if num <= lim: dic.update({num: 0})Additionally,
dic.setdefault(i, dict())has two modes. One for when the input key doesn't exist and one for when it does exists. I believe that within your code you're only ever hitting the latter mode (key doesn't exist), sodic.setdefault(i, dict())can be replaced withdic[i] = dict().Lastly,
dic.update({num: 0})can be replaced withdic[num] = 0which would prevent you from creating the{num: 0}dictionary input todic.update.
- The
if/elsestatements inside theforloop can be removed:
for i in range(1, lim+1):
n = num - i
if n:
dic.setdefault(i, dict())
worker(n, lim, dic[i])
else:
dic.update({i: 0})
break
becomes:
for i in range(1, min(num, lim+1)):
n = num - i
dic.setdefault(i, dict())
worker(n, lim, dic[i])
if num <= lim:
dic.update({num: 0})
- Additionally,
dic.setdefault(i, dict())has two modes. One for when the input key doesn't exist and one for when it does exists. I believe that within your code you're only ever hitting the latter mode (key doesn't exist), sodic.setdefault(i, dict())can be replaced withdic[i] = dict().
- Lastly,
dic.update({num: 0})can be replaced withdic[num] = 0which would prevent you from creating the{num: 0}dictionary input todic.update.
With all those changes, the code becomes: