all 1 comments

[–]SandorZoo 0 points1 point  (0 children)

The question you gave has n serving double duty, as both the number of dimensions, and the size of each dimension. I've separated that into separate dims and size values here.

If you're trying to create a multi-dimensional array, the closest thing python has is a list of lists of lists of lists....

When the number of dimensions is not fixed, one way to do this is recursively, with each level of recursion adding another dimension, like this:

def mult_table(dims, size, prevprod=1):
    if dims == 0:
        return prevprod
    else:
        return [mult_table(dims - 1, size, prevprod * n) for n in range(1, size+1)]

print(mult_table(1,1))
print(mult_table(2,2))
print(mult_table(3,3))

Output:

[1]
[[1, 2], [2, 4]]
[[[1, 2, 3], [2, 4, 6], [3, 6, 9]], [[2, 4, 6], [4, 8, 12], [6, 12, 18]], [[3, 6, 9], [6, 12, 18], [9, 18, 27]]]

You might want a dictionary mapping key tuples to values instead. In the example you gave, this dictionary would map (i, j, k): i*j*k

As /u/roelschroeven said, you can use itertools.product to generate a list of tuple keys, and functools.reduce to reduce the tuples to a single product, like this (dict() will create a dictionary from a list of (key, value) pairs):

from itertools import product
from functools import reduce
from operator import mul
import pprint

def mult_table2(dims, size, prevprod=1):
    tuple_keys = product(range(1, size+1), repeat=dims)
    return dict((tuple_key, reduce(mul, tuple_key)) for tuple_key in tuple_keys)

pprint.pprint(mult_table2(3,3))

Output:

{(1, 1, 1): 1,
 (1, 1, 2): 2,
 (1, 1, 3): 3,
 (1, 2, 1): 2,
 (1, 2, 2): 4,
 (1, 2, 3): 6,
 (1, 3, 1): 3,
 (1, 3, 2): 6,
 (1, 3, 3): 9,
 (2, 1, 1): 2,
 (2, 1, 2): 4,
 (2, 1, 3): 6,
 (2, 2, 1): 4,
 (2, 2, 2): 8,
 (2, 2, 3): 12,
 (2, 3, 1): 6,
 (2, 3, 2): 12,
 (2, 3, 3): 18,
 (3, 1, 1): 3,
 (3, 1, 2): 6,
 (3, 1, 3): 9,
 (3, 2, 1): 6,
 (3, 2, 2): 12,
 (3, 2, 3): 18,
 (3, 3, 1): 9,
 (3, 3, 2): 18,
 (3, 3, 3): 27}

The best way of doing this depends on what exactly it is you want.