Matrix indexing in Python
Question:
I have been trying figure out what this part the code does can anyone explain it me from what i understand the list will be 3,2,1 and then it will print that 3 times but i do not understand what the t[i][i] does in the code the out put is 6 but i do not know how the answer is gotten however if the list were to be printed 4 times of 3 then i have an idea of how the 6 came about
T = [[3-i for i in range (3)] for j in range (3)]
s = 0
for i in range(3):
s += T[i][i]
print(s)
Answers:
I just added some print statements to your code, now I think that you will find it clear what is happening:
from pprint import pprint
T = [[3-i for i in range (3)] for j in range (3)]
print("T matrix:")
pprint(T, width=15)
s = 0
for i in range(3):
s += T[i][i]
print("diagonal item:", T[i][i], "running sum:", s)
print("final sum:", s)
Remember to add print statements to your code when debugging, or use a debugger tool!
Output:
T matrix:
[[3, 2, 1],
[3, 2, 1],
[3, 2, 1]]
diagonal item: 3 running sum: 3
diagonal item: 2 running sum: 5
diagonal item: 1 running sum: 6
final sum: 6
I have been trying figure out what this part the code does can anyone explain it me from what i understand the list will be 3,2,1 and then it will print that 3 times but i do not understand what the t[i][i] does in the code the out put is 6 but i do not know how the answer is gotten however if the list were to be printed 4 times of 3 then i have an idea of how the 6 came about
T = [[3-i for i in range (3)] for j in range (3)]
s = 0
for i in range(3):
s += T[i][i]
print(s)
I just added some print statements to your code, now I think that you will find it clear what is happening:
from pprint import pprint
T = [[3-i for i in range (3)] for j in range (3)]
print("T matrix:")
pprint(T, width=15)
s = 0
for i in range(3):
s += T[i][i]
print("diagonal item:", T[i][i], "running sum:", s)
print("final sum:", s)
Remember to add print statements to your code when debugging, or use a debugger tool!
Output:
T matrix:
[[3, 2, 1],
[3, 2, 1],
[3, 2, 1]]
diagonal item: 3 running sum: 3
diagonal item: 2 running sum: 5
diagonal item: 1 running sum: 6
final sum: 6