+ 2

How can I count the depth of nested list ?

nested([[][][][]])

8th Dec 2020, 1:16 PM
ÄKoderj
16 Answers
+ 3
If u stringified max=0 Level=0 Iterate liststring [ increments level ] decrements it If level > Max then max=level
8th Dec 2020, 6:09 PM
Oma Falk
Oma Falk - avatar
+ 3
Aditya Bhargava Grokking Algorithms: An illustrated guide for programmers and other curious people
9th Dec 2020, 4:48 PM
Oma Falk
Oma Falk - avatar
+ 2
I had a go...but I did it a very long winded way.....then I seen your comment about converting it to a string...that's when the penny dropped...so, after you convert it, loop through the string and use string replace method to replace"[]" with "" (i.e...nothing) and increment a counter.
8th Dec 2020, 6:16 PM
rodwynnejones
rodwynnejones - avatar
+ 2
replace [ by 1 and] by - 1 accumulate the list and find max.
8th Dec 2020, 7:25 PM
Oma Falk
Oma Falk - avatar
+ 2
@Frogged This is from one of the posters comment. "L2=([[[]]])" Although the original post was about ([[][][][]]). I was going to suggest using NumPy.
9th Dec 2020, 10:33 AM
rodwynnejones
rodwynnejones - avatar
+ 1
Suppose I have this list L=([])#it contains 1 bracket L2=([[[]]])#contain 3 empty nested lists . How I can get the number of empty lists.I converted it to str then try to use count func but no vain
8th Dec 2020, 3:03 PM
ÄKoderj
+ 1
rodwynnejones [[][]] depth is 2
8th Dec 2020, 7:33 PM
Oma Falk
Oma Falk - avatar
+ 1
you can solve it with recursion
9th Dec 2020, 2:08 AM
madeline
madeline - avatar
+ 1
#Here the code and comment what the output should be given.my solution isnt correct def count_brackets(lst): f=str(lst) return f.count("[]") print(count_brackets([[[[[[[[[[[]]]]]]]]]]]))#11 print(count_brackets([])) #➞ 1 print(count_brackets([[]])) #➞ 2 print(count_brackets([[[]]])) # ➞ 3
9th Dec 2020, 3:31 PM
ÄKoderj
+ 1
#Frogged Could U please explain to me the method U use to solve it Thanks alot
9th Dec 2020, 3:59 PM
ÄKoderj
+ 1
jäbbar an empty list [] has a depth of 1 A non empty list has a depth of Max depth of its elements + 1
9th Dec 2020, 4:14 PM
Oma Falk
Oma Falk - avatar
0
Are you asking for the number of sub-lists/arrays or the count of elements in the whole list?
8th Dec 2020, 1:48 PM
rodwynnejones
rodwynnejones - avatar
0
Hm.got headache from overthinking to figure it out . Any way thanks alot
8th Dec 2020, 4:22 PM
ÄKoderj
0
#Frogged. Aha .that helps ...I do thank U for Ur help. Now I am trying to develop my logic so am searching for a book . Could U please suggest me a good book that helps me to improve my logic in programming. Much of thanks in advance
9th Dec 2020, 4:20 PM
ÄKoderj