Count ([[[[[[2]]]]]],[[[[2]]]],2) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Count ([[[[[[2]]]]]],[[[[2]]]],2)

How do i implement a function to count number of 2

20th Mar 2020, 3:03 PM
Tan
2 Answers
+ 5
You can use flattening, i have done code for this some months ago. https://code.sololearn.com/cUgNFWGrImML/?ref=app
20th Mar 2020, 3:55 PM
Lothar
Lothar - avatar
+ 4
If you don't know how many nested levels your list might have, recursion is always a good option. Set the count to 0 Loop through each element in the list If the element is a number, add it to the count If its a list, do the recursion Finally return the count. One technique to determine if something is a list or not, is duck typing. Try to iterate, if you get an error then it is not iterable.
20th Mar 2020, 3:12 PM
Tibor Santa
Tibor Santa - avatar