Created
May 25, 2017 17:24
-
-
Save sxslex/dd15b13b28c40e695f1e227a200d1646 to your computer and use it in GitHub Desktop.
Elegant Python code for Integer Partitioning
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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 | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
umm it takes a lot of time to find partition of larger numbers,
check the the one i did: https://github.com/SK000001/partition