Re: List partitioning
- From: Boris Borcic <bborcic@xxxxxxxxx>
- Date: Sun, 26 Oct 2008 18:04:28 +0100
bim wrote:
pineapple.link@xxxxxxxxx wrote :Sounds like a homework assignment.
It's not, I left studies years ago...
I just need a balancing algorithm for a program of mine, and I wonder if it wouldn't be easier to do it in Prolog.
Then maybe a Python version would serve.
NB :
- Python 2.6 (itertools.combinations, product)
- lightly tested
HTH, BB
from itertools import tee,combinations,imap,product
def partEvenly(aSet,nCombis) :
if aSet :
item=min(aSet)
while 1 :
smallSet = nCombis.next()
if item<min(smallSet) : break
if smallSet<=aSet :
furtherCombis, nCombis = tee(nCombis)
for further in partEvenly(aSet-smallSet,
furtherCombis) :
further.append(smallSet)
yield further
else :
yield []
def combi(u,n) :
return imap(set,combinations(u,n))
def partition(n,m) :
aSet = set(range(n))
j,k = divmod(n,m)
if k :
return (x+y
for jU in combi(aSet,j*(m-k))
for x,y in product(*(partEvenly(U,combi(U,J))
for U,J in [(jU,j),(aSet-set(jU),j+1)]))
)
else :
return partEvenly(aSet,combi(range(n),j))
>>> for res in partition(5,2) :
print sorted(sorted(sset) for sset in res)
[[0, 1], [2, 3, 4]]
[[0, 2], [1, 3, 4]]
[[0, 3], [1, 2, 4]]
[[0, 4], [1, 2, 3]]
[[0, 3, 4], [1, 2]]
[[0, 2, 4], [1, 3]]
[[0, 2, 3], [1, 4]]
[[0, 1, 4], [2, 3]]
[[0, 1, 3], [2, 4]]
[[0, 1, 2], [3, 4]]
.
- Follow-Ups:
- Re: List partitioning
- From: bim
- Re: List partitioning
- From: Markus Triska
- Re: List partitioning
- References:
- List partitioning
- From: BimKif
- Re: List partitioning
- From: pineapple . link
- Re: List partitioning
- From: bim
- List partitioning
- Prev by Date: Re: List partitioning
- Next by Date: Re: List partitioning
- Previous by thread: Re: List partitioning
- Next by thread: Re: List partitioning
- Index(es):
Relevant Pages
|