Complete-Python-Mastery
Complete-Python-Mastery copied to clipboard
Find pairs with given sum such that elements of pair are in different rows in Python
Input : mat[4][4] = {{1, 3, 2, 4},
{5, 8, 7, 6},
{9, 10, 13, 11},
{12, 0, 14, 15}}
sum = 11
Output: (1, 10), (3, 8), (2, 9), (4, 7), (11, 0)
mat = [[1, 3, 2, 4],
[5, 8, 7, 6],
[9, 10, 13, 11],
[12, 0, 14, 15]]
n_row = len(mat) # to find no of rows in Python matrix / 2 d list
n_col = len(mat[0]) # to find no. of columns in Python matrix / 2 d list
# print(n_row)
# print(n_col)
for i in range(0, n_row):
for j in range(0, n_col):
for k in range(i+1, n_row):
for l in range(0, n_col):
if k == n_row :
break # this ensures that the row indexes do not go out of bounds
else:
if mat[i][j] + mat[k][l] == 11:
print(mat[i][j], " & ", mat[k][l])