Python Forum

Full Version: Homework-excercise
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I'm a student to 1st semester and I have a problem to solve:
"Create a 5x5 random number table and calculate the sum of items per line, per column, and the sum of the elements in the diagonal table. Save the results to a text file."
This is my code until to the sum of items per line. After that I'm stuck!

import random

f=[]
 
for i in range (5):
    line = []
    for j in range (5):
        line.append(random.randint(1,10))
    f.append(line)
 
for each in f:
    print(each)
    print (sum(each))
If anyone knows please reply.
Thanks in advance,
gmit
Please edit your post so the code is in Python code tags. You can find help here. Also, when you copy code, use ctrl+shift+v to preserve indentation.

Edit:
Uuggghhhhh I had quite an answer written here... probably got deleted during server maintenance. :D And I think OP also edited code tags, so I'm putting them back.
I'll make it short this time. To sum columns and diagonals, you can iterate through the lines (lists within list). You can access a list element with my_list[0] to get first element, my_list[1] to get second etc... And since you have nested lists (lines in the matrix), you will need, e.g., matrix[0][2] to access 3rd element in first list (first line).
I recommend you to give variables a descriptive name, code will be more readable and maintainable (e.g. matrix instead of f). It is a general recommendation as well.
f=[]

for i in range (5):
    line = []
    for j in range (5):
        line.append(random.randint(1,10))
    f.append(line)

for each in f:
    print(each)
    print (sum(each))
Output:
[10, 7, 6, 2, 9] 34 [3, 8, 4, 7, 1] 23 [1, 2, 10, 5, 1] 19 [3, 3, 2, 9, 10] 27 [10, 1, 5, 4, 1][10, 7, 6, 2, 9] 34 [3, 8, 4, 7, 1] 23 [1, 2, 10, 5, 1] 19 [3, 3, 2, 9, 10] 27 [10, 1, 5, 4, 1] 21 21
It works. Maybe you made a mistake with indentation.