Skip to content

Instantly share code, notes, and snippets.

@alexholehouse
Last active December 4, 2018 17:03
Show Gist options
  • Save alexholehouse/6190193 to your computer and use it in GitHub Desktop.
Save alexholehouse/6190193 to your computer and use it in GitHub Desktop.
n-dimensional arrays in Python
## Function to create an n-dimensional array
# Main function to call
# typeOfitem
# Should be a class which can generate objects
# e.g. float, int, complex, or any other type, such as
# myCoolClass
#
# dimensions
# value for a 1D array, or a list or tuple defining the
# dimensions, for higher order arrays. e.g. a 3D array
# might be [2,3,4]
#
def nDarray(typeOfitem, dimensions):
depth = 0
if type(dimensions) == int:
dimensions = [dimensions]
return(recursiveAllocator(typeOfitem,dimensions,depth))
# recursive internal function
def recursiveAllocator(basetype, dimensionList, depth):
# Base case
if depth == len(dimensionList)-1:
currentDimension = dimensionList[depth]
array = []
for i in xrange(0,currentDimension):
array.append(basetype())
return array
# Recursive case
else:
array=[]
currentDimension = dimensionList[depth]
# for each element in each dimension recursivly
# call the function
for i in xrange(0,currentDimension):
array.append(recursiveAllocator(basetype,dimensionList, depth+1))
return array
@prakharcode
Copy link

def nd(n):
    a = lambda x: [random.random() for i in range(n)] if x==1 else [a(x-1) for _ in range(n)]
    return a(n)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment