Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Homework-excercise
#1
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
Reply
#2
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.
Reply
#3
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with the excercise alani 3 2,134 Apr-19-2020, 07:29 PM
Last Post: deanhystad
  Program excercise SushiRolz 1 2,452 Feb-28-2018, 01:48 AM
Last Post: Larz60+
  excercise python list Kykoss 7 3,994 Feb-11-2018, 03:08 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020