How to compute column and row totals in python tables

#1

I have managed to create a python table.
However i cannot create two separate functions .say def row_totals() and def column_total()
and a table being an argument.

Here is my code:
ROWS = 5
COLUMNS = 3

list of teams names

teams = ["Team A",
"Team B",
"Team C",
"Team D",
"Team E"]

a table of points it each year .

points = [ [ 60, 55,50 ],
[ 70, 80,40 ],
[ 45, 65,90 ],
[ 50, 70,80 ],
[ 80, 75,60 ]

``       ]``

print(" 2011 2013 2014")
for i in range(ROWS):
print("%10s" %teams[i],end= "")
for j in range(COLUMNS):
print("%6d" %points[i][j],end="")
print()

#2

What prevents you from creating two separate functions?

If the title is your question, then what represents a row in your program? What represents a column? How would you add a row? How would you add a column? Are those things that can be inspected? If each value in a list represents a row, then would the number of rows not be the length of that list? And if you inspect a row, what would its length be?

#3

Have you run that code?

#4

Is this how the table is to be represented?

``````        2011 2013 2014
Team A   60   55   50
Team B   70   80   40
Team C   45   65   90
Team D   50   70   80
Team E   80   75   60``````

To add up the row, what handy built-in does Python offer for this purpose?

The columns will require a little bit of thought, but don't over think it. What does each row have in common? Hint: column index.

#5

That is the correct table.eg Team A will have total points of 165 if you add points in those 3 yrs( row totals).Likewise in 2014 all teams in total collected points 320( a column total. Use only list and range function.in built function are not required so as set tuple and dict

#6

Do you mean like so,

``````        2011 2013 2014 total
Team A   60   55   50   165
Team B   70   80   40   190
Team C   45   65   90   200
Team D   50   70   80   200
Team E   80   75   60   215
Total   305  345  320``````

#7

Perfect mtf. How did you do that.Could not everything was an error for me.Was trying to write a function with a table as an argument then calling that function so that i can get total of column.

#8

I gave you a hint about the row totals, so I won't give that away.

For the column total, define a list variable and give it three elements, set to 0.

``col_total = [0, 0, 0]``

Inside the `j` loop, accumulate each column of this list. Outside of the loops, print the last line.

#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.