Pankaj-Str / Complete-Python-Mastery

Explore the world of Python programming with 'Complete Python Mastery'! Our repository, led by Pankaj, offers a series of in-depth tutorials under the banner 'Codes with Pankaj.' Dive into hands-on coding examples, insightful explanations, and practical projects as Pankaj guides you through mastering Python.
https://www.codeswithpankaj.com/
32 stars 24 forks source link

Find pairs with given sum such that elements of pair are in different rows in Python #1

Open Pankaj-Str opened 1 year ago

Pankaj-Str commented 1 year ago
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) 
AnmolDixitB13 commented 3 months ago

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])