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/flatten_deep_list.py at master · vedsgit/coding-problems

Expand file tree

/

flatten_deep_list.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
47 lines (34 loc) · 1.43 KB
/

flatten_deep_list.py

Copy path

File metadata and controls

47 lines (34 loc) · 1.43 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
'''
Flatten an Arbitrarily Deep List
Given a list that can contain arbitrary lists as its elements, which in turn can contain arbitrary lists
as elements, and so on, create and return a new list that contains all the atomic (that is, anything
that is not a list) elements listed in a linear sequence without any nesting.
Input: [1, [2, 3, [4, 'bob', 6], [7]], [8, 9]]
Output: [1, 2, 3, 4, 'bob', 6, 7, 8, 9]
=========================================
Recursive solution, extend the result with each sublist.
Time Complexity: O(N)
Space Complexity: O(N)
'''
############
# Solution #
############
def flatten_deep_list(arr):
if not isinstance(arr, list):
return [arr]
result = []
for a in arr:
result.extend(flatten_deep_list(a))
return result
###########
# Testing #
###########
# Test 1
# Correct result => [1, 2, 3, 4, 'bob', 6, 7, 8, 9]
print(flatten_deep_list([1, [2, 3, [4, 'bob', 6], [7]], [8, 9]]))
# Test 2
# Correct result => [89, 85, 72, 84, 65, 88, 31, 64, 11, 60, 42, 57, 55, 16, 79, 34, 82, 94, 36, 89, 26, 39, 94, 47, 72, 30, 72, 3, 73, 18, 37, 51, 75, 83, 94, 57, 37, 10, 62, 62, 13]
print(flatten_deep_list([[], [[[[89, 85, 72, 84, 65], [[88, 31, 64, 11, 60, 42, 57, 55], 16, [79, 34, 82], [], 94, 36, [89, 26, 39, 94, 47, 72, 30], [72, 3, 73]], 18]], [[37, [51, 75, 83], 94, 57]], [37, 10, 62, 62], [[], 13]]]))
# Test 3
# Correct result => [ ]
print(flatten_deep_list([ [ [ [ [ [ ] ] ] ] ] ]))
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.