I am trying to create a function that will make a multidimensional list taking an input number to choose the amount of dimensions the list will be. This is my code so far:
def createMultiDimList(dimensions, currentDim=0, output=[]):
if currentDim < dimensions:
output.append([])
currentDim = 1
createMultiDimList(dimensions, currentDim, output[0])
return output
else:
return output
I think this isn't working because the recursion is just putting in the single dimensional list, but I am not sure on that.
CodePudding user response:
You're overcomplicating it IMO. The general idea behind recursion is to solve the easiest case first, and then return the result of the more difficult case in terms of an incrementally easier case.
For this function, the "easy case" is that a 1-dimensional list is []
. The incrementally easier case is that an n
-dimensional list is an n-1
-dimensional list inside a list. Hence:
>>> def n_dim_list(n: int) -> list:
... if n == 1:
... return []
... return [n_dim_list(n-1)]
...
>>> n_dim_list(4)
[[[[]]]]
If you wanted to complicate it a bit to make it a more interesting example of recursion, you could define a filler value for the 1-dimensional lists and the length of each list:
>>> def n_dim_list(n: int, length: int = 0, value = None) -> list:
... if n == 1:
... return [value] * length
... return [n_dim_list(n-1, length, value) for _ in range(length or 1)]
...
>>> n_dim_list(4)
[[[[]]]]
>>> n_dim_list(4, 2, 0)
[[[[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]]
CodePudding user response:
as @Samwise wisely said, you have simpled awesome approuch like his, specifically for your issue, you need to send down nested list instead of appending item and returning it:
def createMultiDimList(dimensions, currentDim=0, output=[]):
if currentDim < dimensions:
currentDim = 1
createMultiDimList(dimensions, currentDim, [output])
return output
else:
return output