-
Notifications
You must be signed in to change notification settings - Fork 0
/
16_Deep Count.py
executable file
·44 lines (28 loc) · 1.11 KB
/
16_Deep Count.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Deep Count
# The built-in len operator outputs the number of top-level elements in a List,
# but not the total number of elements. For this question, your goal is to count
# the total number of elements in a list, including all of the inner lists.
# Define a procedure, deep_count, that takes as input a list, and outputs the
# total number of elements in the list, including all elements in lists that it
# contains.
# For this procedure, you will need a way to test if a value is a list. We have
# provided a procedure, is_list(p) that does this:
def is_list(p):
return isinstance(p, list)
# It is not necessary to understand how is_list works. It returns True if the
# input is a List, and returns False otherwise.
def deep_count(p):
size=len(p)
for i in p:
if is_list(i):
size+=deep_count(i)
return size
print deep_count([1, 2, 3])
#>>> 3
# The empty list still counts as an element of the outer list
print deep_count([1, [], 3])
#>>> 3
print deep_count([1, [1, 2, [3, 4]]])
#>>> 7
print deep_count([[[[[[[[1, 2, 3]]]]]]]])
#>>> 10