• API
• FAQ
• Tools
• Archive
SHARE
TWEET

# Untitled

a guest Apr 21st, 2019 84 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. import sys
2. from collections import deque
3.
4.
5. def flatten(nested_list):
6.     """Flatten a list of nested lists of integers into a flat list of integers."""
7.     result = []
8.     nested_deque = deque(nested_list)
9.
10.     while nested_deque:
11.         sublist = nested_deque.popleft()
12.
13.         if isinstance(sublist, list):
14.             nested_deque.extendleft(reversed(sublist))
15.         else:
16.             result.append(sublist)
17.     return result
18.
19.
20. if __name__ == "__main__":
21.     assert flatten([]) == []
22.     assert flatten([1]) == [1]
23.     assert flatten([1, 2]) == [1, 2]
24.     assert flatten([1, [2]]) == [1, 2]
25.     assert flatten([1, [2, [3]]]) == [1, 2, 3]
26.     assert flatten([[[[1]]], [[[2]]], [[[3]]]]) == [1, 2, 3]
27.
28.     # verify a list with depth greater than python's recursion limit
29.     # recursive flattening wouldn't pass this test:
30.     deeply_nested_list = [1, 2, 3]
31.     for i in range(sys.getrecursionlimit() + 1):
32.         deeply_nested_list[0] = [deeply_nested_list[0]]
33.     assert flatten(deeply_nested_list) == [1, 2, 3]
34.
35.     # long nested list:
36.     assert flatten([[[[[i]]]] for i in range(100000)]) == list(range(100000))
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top