For a school task I need to display a nxn matrix depending on users input:
heres an example:
0 0 0 0 1
0 0 0 1 0
0 0 1 0 0
0 1 0 0 0
1 0 0 0 0
(users input: 5)
And here is my code until now:
n = int(input("please enter a number: "))for i in range( 1,n+1):for j in range(1,n+1):print(0, end = " ")print('\n')
So it only displays zero in my matrix,
but how can I implement the one switching one position in each line?
- First, try to find the relation or pattern happend when there is '1' in matrix, you will find that if (row_number + column_number = n - 1) then there is '1'
row=[]
you will make empty list to add the values of each row in it, notice that you will put row=[]
inside for row_number in range(n):
to make empty list after finish each row.
if row_number+column_number == n-1:
this is the pattern happens when there is '1', so if condition is true there is 1
will be appended in the row
, and if condition is false there is 0
will be appended in the row
.
print(*row)
i use *
to unpack the elements of list
n = int(input("please enter a number: "))for row_number in range(n):row = []for column_number in range(n):if row_number+column_number == n-1:row.append(1)else:row.append(0)print(*row)
Output
please enter a number: 5
0 0 0 0 1
0 0 0 1 0
0 0 1 0 0
0 1 0 0 0
1 0 0 0 0