GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — coding-problems/Arrays/reverse_all_lists.py at master · vedsgit/coding-problems

Expand file tree

/

reverse_all_lists.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
72 lines (53 loc) · 1.67 KB
/

reverse_all_lists.py

Copy path

File metadata and controls

72 lines (53 loc) · 1.67 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'''
Reverse All Lists
Return a list that contains the items in reverse, but so that whenever each item is
itself a list, its elements are also reversed. This reversal of sublists must keep going on all the way
down, no matter how deep the nesting of these lists,
Input: [1, [2, 3, 4, 'yeah'], 5]
Output: [5, ['yeah', 4, 3, 2], 1]
=========================================
This problem can be solved using queue, stack (or recursion). Use in place reversing and save all
inner lists for reversing later.
Time Complexity: O(N)
Space Complexity: O(1)
'''
############
# Solution #
############
from collections import deque
def reverse_all_lists(arr):
queue = deque()
queue.append(arr)
while queue:
inner_arr = queue.popleft()
# in place reverse
reverse_arr(inner_arr)
# take all inner lists and save them for later
for item in inner_arr:
if isinstance(item, list):
queue.append(item)
return arr
def reverse_arr(arr):
start = 0
end = len(arr) - 1
while start < end:
# reverse the array from the start index to the end index by
# swaping each element with the pair from the other part of the array
swap(arr, start, end)
start += 1
end -= 1
return arr
def swap(arr, i, j):
# swapping two elements from a same array
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
###########
# Testing #
###########
# Test 1
# Correct result => [5, ['yeah', 4, 3, 2], 1]
print(reverse_all_lists([1, [2, 3, 4, 'yeah'], 5]))
# Test 2
# Correct result => [[[[['boo!'], 33], 17], 99], 42]
print(reverse_all_lists([42, [99, [17, [33, ['boo!']]]]]))
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.