[Tutor] initialising all elements of a matrix
Peter Otten
__peter__ at web.de
Tue Feb 28 17:40:17 CET 2012
Sivaram Neelakantan wrote:
>
> I was wondering whether there is a faster/better/cleaner way of
> element wise operations of arbitrarily nested list. I wrote something
> like this for 1 level nested lists and am wondering whether there are
> any good idioms in python. I did this after a ridiculous amount of
> bad thinking/missteps in python for the simplest of cases.
>
> def init_p (arr):
> # input is always 2D matrix; init to uniform probability dist.
> q = []
> row = len(arr)
> col = len(arr[0])
> uni_dist = 1.0/(row *col)
> q = [ [uni_dist] * col for i in range(row)]
> return q
>
> Of course, without using external packages like numpy or any other
> scientific packages.
Here's how I would break up the problem:
# untested
def nested_list(shape, value):
if len(shape) == 1:
return [value] * shape[0]
return [nested_list(shape[1:], value) for _ in range(shape[0])]
def get_shape(arr):
shape = []
while isinstance(arr, list):
shape.append(len(arr))
arr = arr[0]
return shape
def product(factors, product=1):
for factor in factors:
product *= factor
return product
def init_p(arr):
shape = get_shape(arr)
value = 1.0 / product(shape)
return nested_list(shape, value)
Now you can proceed to improve the parts independently...
More information about the Tutor
mailing list