Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SamirPaulb/6aa5665a2b7123b9cef0466cabb5e7fe to your computer and use it in GitHub Desktop.
Save SamirPaulb/6aa5665a2b7123b9cef0466cabb5e7fe to your computer and use it in GitHub Desktop.
# print all elements of a matrix with a Single loop
arr = [[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
# Method 1
row = len(arr)
col = len(arr[0])
i = 0
for i in range(row * col): # i < number of rows * number of columns
r = i // col
c = i % col
print(arr[r][c], end = ", ")
###
print()
###
# Method 2
i, j = 0, 0
while i < len(arr):
print(arr[i][j], end=", ")
j += 1
if j == len(arr[0]):
j = 0
i += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment