YashuC ッ
YashuC ッ

Reputation: 81

How to print a matrix with a certain pattern in python

How can we create a pattern using Python which will create a square Matrix it will put values of diagonal elements equal to zero change the value of elements above diagonal elements 29 and change the values below that a diagonal equals to 5.

For example:


Input: 4

Output:

0999
5099
5509
5550

Please Help. Thanks

Upvotes: 0

Views: 1773

Answers (5)

sahasrara62
sahasrara62

Reputation: 11228

You need to check the condition for , diagonal (row_index == column_index), upper triangular matrix (column_index > row_index) and lower_triangular matrix (row_index > column_index) and then add values accordingly

def func(n):
    l = []
    for i in range(n):
        tmp = []
        for j in range(n):
            if j==i:
                tmp.append(0)
            elif j>i:
                tmp.append(9)
            elif j<n:
                tmp.append(5)
        l.append(tmp)
    return l

Upvotes: 1

Hemant
Hemant

Reputation: 1156

I think this should do the trick

def pattern(size):
    for i in range(size):
        print('5'*i + '0' + '9'*(size-i-1))
        
pattern(4)

Upvotes: 1

Jiř&#237; Baum
Jiř&#237; Baum

Reputation: 6930

The key phrases to search for are "upper triangle" and "lower triangle". Once that's done, we can compose the desired output like this:

import numpy as np

shape = (4, 4)
np.tril(np.full(shape, 5), -1) + np.triu(np.full(shape, 9), 1)

How this works:

  • np.full(shape, fill_value) constructs an array of the given shape, filled with the given number.
  • np.tril(m, k) returns the lower triangle of the matrix m, from the kth diagonal (with the rest zeroed).
  • Similarly, np.triu(m, k) returns the upper triangle of the matrix m, from the kth diagonal (with the rest zeroed).

Upvotes: 1

Ayush
Ayush

Reputation: 160

If you just have to print, you can try following

for i in range(n):
    for j in range(n):
        # diagonal case
        if i == j:
            print(0, end='')
        # upper diagonal case
        elif i < j:
            print(9, end='')
        # lower diagonal case
        else:
            print(5, end='')
    print('')

Upvotes: 2

Addicted2Cookies
Addicted2Cookies

Reputation: 84

Try using the numpy library.

import numpy as np

np.identity(4) # This will print out 1 on the diagnoals and 0 on the rest.

After that just use a loop to change all the 1s (diagnoals) to 0s Then use if statements and loops to identify whether a number is above the 0 or not

Or if you just want to use a matrix with a predefined list, then just use np.array(list)

Upvotes: 1

Related Questions