+ 2
How can I count the depth of nested list ?
nested([[][][][]])
16 Antworten
+ 3
If u stringified
max=0
Level=0
Iterate liststring
[ increments level
] decrements it
If level > Max then max=level
+ 3
Aditya Bhargava
Grokking Algorithms: An illustrated guide for programmers and other curious people
+ 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.
+ 2
replace [ by 1 and] by - 1
accumulate the list and find max.
+ 2
@Frogged
This is from one of the posters comment.
"L2=([[[]]])"
Although the original post was about ([[][][][]]).
I was going to suggest using NumPy.
+ 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
+ 1
rodwynnejones [[][]]
depth is 2
+ 1
you can solve it with recursion
+ 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
+ 1
#Frogged
Could U please explain to me the method U use to solve it
Thanks alot
+ 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
0
Are you asking for the number of sub-lists/arrays or the count of elements in the whole list?
0
Hm.got headache from overthinking to figure it out .
Any way thanks alot
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