Last active
December 4, 2018 17:03
-
-
Save alexholehouse/6190193 to your computer and use it in GitHub Desktop.
n-dimensional arrays in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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
commented
Dec 4, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment