-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeep_reverse.py
More file actions
39 lines (30 loc) · 1 KB
/
deep_reverse.py
File metadata and controls
39 lines (30 loc) · 1 KB
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
# Question 9: Deep Reverse
# Define a procedure, deep_reverse, that takes as input a list,
# and returns a new list that is the deep reverse of the input list.
# This means it reverses all the elements in the list, and if any
# of those elements are lists themselves, reverses all the elements
# in the inner list, all the way down.
# Note: The procedure must not change the input list.
# The procedure is_list below is from Homework 6. It returns True if
# p is a list and False if it is not.
def is_list(p):
return isinstance(p, list)
def deep_reverse(old_list):
new_list = []
for p in old_list:
if isinstance(p, list):
new_list = [deep_reverse(p)] + new_list
else:
new_list = [p] + new_list
return new_list
# For example,
p = [1, [2, 3, [4, [5, 6]]]]
print deep_reverse(p)
# >>> [[[[6, 5], 4], 3, 2], 1]
print p
# >>> [1, [2, 3, [4, [5, 6]]]]
q = [1, [2, 3], 4, [5, 6]]
print deep_reverse(q)
# >>> [ [6,5], 4, [3, 2], 1]
print q
# >>> [1, [2,3], 4, [5,6]]