# 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(p): q = [] if not p: return 0 for i in p: q.append(i) r = [] item = q.pop() if is_list(item): r.append(deep_reverse(item)) else: deep_reverse(q) return r #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]]
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question