0

We can create multi-dimensional arrays in python by using nested list, such as:

A = [[1,2,3],
     [2,1,3]]

etc. In this case, it is simple nRows= len(A) and nCols=len(A[0]). However, when I have more than three dimensions it would become complicated.

A = [[[1,1,[1,2,3,4]],2,[3,[2,[3,4]]]],
     [2,1,3]]

etc. These lists are legal in Python. And the number of dimensions is not a priori. In this case, how to determine the number of dimensions and the number of elements in each dimension.

I'm looking for an algorithm and if possible implementation. I believe it has something similar to DFS. Any suggestions?

P.S.: I'm not looking for any existing packages, though I would like to know about them.

6
  • 2
    Your second example is inconsistently multi-dimensional. Consider using numpy for this sort of thing, where you can just ask for an object's shape. Commented Oct 17, 2014 at 14:37
  • What you want is more of a tree than an array (it is not even a jagged array). For it to be an array, you should have a list of lists of values, and not a list of values OR other lists. The very definition of tree is a structure where every node has a collection where each item is a leaf or another node, thus being recursive. Commented Oct 17, 2014 at 14:37
  • I know that the example given is inconsistently multi-dimensional. Consider a case, if we want to check a given data is a proper array (if you need a practical example) However, as I had mentioned later, the objective is find the algorithm. I'm aware of numpy.py but I'm looking for the algorithm. Commented Oct 17, 2014 at 14:40
  • @heltonbiker: I agree with you. It is more like a tree than an array. We could construct a tree in this case and probably determine the dimensions, as values in each node. But that would be slow. I'm looking for an efficient algorithm... Not using packages like numpy or SciPy. Commented Oct 17, 2014 at 14:44
  • If you apply the algorithm to this example you posted, what would be the result, and why? Commented Oct 17, 2014 at 18:26

1 Answer 1

0

I believe to have solve the problem my self. It is just a simple DFS.

For the example given above: A = [[[1,1,[1,2,3,4]],2,[3,[2,[3,4]]]], [2,1,3]] the answer is as follows: [[3, 2, 2, 2, 3, 4], [3]] The total number of dimensions is the 7.

I guess I was overthinking... thanks anyway...!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.