Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 81f6c64

Browse files
Create flatten_2d_List.md
1 parent 1924904 commit 81f6c64

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

‎snippets/python/flatten_2d_List.md‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Flatten 2D List
2+
3+
*tags: * python
4+
5+
```
6+
# The function is expected to return a STRING.
7+
# The function accepts 2D_INTEGER_ARRAY matrix as parameter.
8+
# Input: [[1,2,3],[4,5,6],[7,8,9]]
9+
# output: [1,2,3,4,5,6,7,8,9]
10+
11+
l = []
12+
def flatten_array(matrix):
13+
return ",".join(flat(matrix, 0, 0))
14+
15+
def flat(matrix, row, col):
16+
l.append(str(matrix[row][col]))
17+
if col == len(matrix[row]) - 1:
18+
if row == len(matrix) - 1:
19+
return l
20+
return flat(matrix, row + 1, 0)
21+
return flat(matrix, row, col + 1)
22+
23+
24+
print("Enter number of rows: ", end="")
25+
matrix_rows = int(input().strip())
26+
print("Enter number of columns: ", end="")
27+
matrix_columns = int(input().strip())
28+
29+
matrix = []
30+
print("Enter matrix elements:")
31+
for _ in range(matrix_rows):
32+
matrix.append(list(map(int, input().rstrip().split())))
33+
print("Entered matrix is: ", matrix)
34+
35+
result = flatten_array(matrix)
36+
print("Resultant list: [", end="")
37+
print(result, end="]")
38+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /