[Numpy-discussion] Numpy newbie question: matrix creation
Robert Kern
robert.kern at gmail.com
Wed Sep 25 08:38:22 EDT 2013
On Wed, Sep 25, 2013 at 1:12 PM, Edmondo Porcu <edmondo.porcu at gmail.com>
wrote:
>
> That's what I was looking for, except that I want to be sure to generate
all the possible combinations, and to have no repeated values.
Okay, then you need to find all of the integer partitions of 10 with
`ncols` elements (padding with 0s for those partitions with fewer than
`ncols` elements), finding the permutations of each padded partition, then
eliminating duplicates.
import itertools
import numpy as np
def gen_partitions(n):
""" Generate integer partitions for `n`.
http://homepages.ed.ac.uk/jkellehe/partitions.php
"""
a = [0 for i in range(n + 1)]
k = 1
y = n - 1
while k != 0:
x = a[k - 1] + 1
k -= 1
while 2*x <= y:
a[k] = x
y -= x
k += 1
l = k + 1
while x <= y:
a[k] = x
a[l] = y
yield a[:k + 2]
x += 1
y -= 1
a[k] = x + y
y = x + y - 1
yield a[:k + 1]
def gen_permuted_partitions(ncols, n=10):
for partition in gen_partitions(n):
partition = list(partition)
if len(partition) > ncols:
continue
partition.extend([0] * (ncols - len(partition)))
for x in itertools.permutations(partition):
yield x
def compute_matrix(ncols):
return np.array(sorted(set(gen_permuted_partitions(ncols)))) / 10.0
--
Robert Kern
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20130925/945fd97d/attachment.html>
More information about the NumPy-Discussion
mailing list