Skip to content

Commit 7392267

Browse files
committed
TR updates, first round
1 parent 168e66a commit 7392267

File tree

2 files changed

+17
-17
lines changed

2 files changed

+17
-17
lines changed

python-flatten-list/flatten.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,11 @@
33
from operator import add, concat, iconcat
44

55

6-
def flatten_comprehension(matrix):
7-
return [item for row in matrix for item in row]
6+
def flatten_extend(matrix):
7+
flat = []
8+
for row in matrix:
9+
flat.extend(row)
10+
return flat
811

912

1013
def flatten_concatenation(matrix):
@@ -14,17 +17,18 @@ def flatten_concatenation(matrix):
1417
return flat
1518

1619

17-
def flatten_extend(matrix):
18-
flat = []
19-
for row in matrix:
20-
flat.extend(row)
21-
return flat
20+
def flatten_comprehension(matrix):
21+
return [item for row in matrix for item in row]
2222

2323

24-
def flatten_itertools_chain(matrix):
24+
def flatten_chain(matrix):
2525
return list(chain.from_iterable(matrix))
2626

2727

28+
def flatten_reduce_lambda(matrix):
29+
return list(reduce(lambda x, y: x + y, matrix, []))
30+
31+
2832
def flatten_reduce_add(matrix):
2933
return reduce(add, matrix, [])
3034

@@ -37,9 +41,5 @@ def flatten_reduce_iconcat(matrix):
3741
return reduce(iconcat, matrix, [])
3842

3943

40-
def flatten_reduce_lambda(matrix):
41-
return list(reduce(lambda x, y: x + y, matrix, []))
42-
43-
4444
def flatten_sum(matrix):
4545
return sum(matrix, [])

python-flatten-list/performance.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,15 @@
66
TO_MS = 1000
77
NUM = 10
88
FUNCTIONS = [
9-
"flatten_comprehension",
10-
"flatten_concatenation",
119
"flatten_extend",
10+
"flatten_concatenation",
11+
"flatten_comprehension",
12+
"flatten_chain",
1213
"flatten_reduce_lambda",
13-
"flatten_sum",
14-
"flatten_itertools_chain",
1514
"flatten_reduce_add",
1615
"flatten_reduce_concat",
1716
"flatten_reduce_iconcat",
17+
"flatten_sum",
1818
]
1919

2020
matrix = [list(range(SIZE))] * SIZE
@@ -27,4 +27,4 @@
2727
print(f"Time to flatten a {SIZE}x{SIZE} matrix (in milliseconds):\n")
2828

2929
for func, time in sorted(results.items(), key=lambda result: result[1]):
30-
print(f"{func + '()':.<30}{time * TO_MS / NUM:.>10.6f} ms")
30+
print(f"{func + '()':.<30}{time * TO_MS / NUM:.>7.2f} ms")

0 commit comments

Comments
 (0)