Skip to content

Commit c87a80d

Browse files
Added Flatten2D.py
1 parent 4d16573 commit c87a80d

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

snippets/python/Flatten2D.py

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

0 commit comments

Comments
 (0)