Skip to content

Instantly share code, notes, and snippets.

@sxslex
Created May 25, 2017 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sxslex/dd15b13b28c40e695f1e227a200d1646 to your computer and use it in GitHub Desktop.
Save sxslex/dd15b13b28c40e695f1e227a200d1646 to your computer and use it in GitHub Desktop.
Elegant Python code for Integer Partitioning
# -*- coding: utf-8 -*-
import timeit
ncache = 0
cache = {}
def partition(number):
global cache, ncache
answer = {(number,), }
if number in cache:
ncache += 1
return cache[number]
if number == 1:
cache[number] = answer
return answer
for x in range(1, number):
for y in partition(number - x):
answer.add(tuple(sorted((x, ) + y)))
cache[number] = answer
return answer
print('To 5:')
for r in sorted(partition(5))[::-1]:
print('\t' + ' + '.join(str(i) for i in r))
print(
'Time: {}\nCache used:{}'.format(
timeit.timeit(
"print('To 30: {} possibilities'.format(len(partition(30))))",
setup="from __main__ import partition",
number=1
), ncache
)
)
@SK000001
Copy link

SK000001 commented Jun 5, 2022

umm it takes a lot of time to find partition of larger numbers,
check the the one i did: https://github.com/SK000001/partition

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment