python coding sum the rows and columns of a grid -


i trying use spread sheet format in python coding. trying teach junior high school students how read table matrix.txt file , produce set of rows , columns. want them see if sum of each column matches sum given , same rows. here putting in matrix.txt file

3 3 7 2 5 14 6 3 1 10 3 9 8 20 16 14 14 

here code have constructed far cant head around how program calculate sum of each rows first 3 (number of rows) integers. hope can help.

k=[] open('matrix.txt') f:   grid_data = [i.split() in f.readlines()] el in grid_data[0:]:   num in el[0]:      k.append(num) row=int(k[0]) in range(1,row):   el in grid_data[i]:     print(sum(el[0:row-1]))  

if there better way solve please let me know. past unsw coding comp question 2014. love cool way analysis tables or grids in python.

numpy total overkill such simple problem, , require dump whole bunch of background learning on young students.

i don't spoon-feeding, there many elements pythonic solution readily explain in prose, here's code:

with open('matrix.txt') f:     # skip dims because redundant.     f.readline()      # convert int read.     grid = [map(int, i.split()) in f]  # define convenience vars (also efficiency - rows evaluated twice). rows = grid[:-1] totals = grid[-1]  # verify row totals. (r, row) in enumerate(rows):     assert sum(row[:-1]) == row[-1], 'row {}'.format(r)  # verify column totals. (c, total) in enumerate(totals):     assert sum(row[c] row in rows) == total, 'col {}'.format(c) 

edit: blue reminded me of nice pythonic trick transposing array. end result more elegant:

# replace convenience down with…  # verify row totals. (r, row) in enumerate(grid[:-1]):     assert sum(row[:-1]) == row[-1], 'row {}'.format(r)  # verify column totals. (c, col) in enumerate(zip(*grid)[:-1]):     assert sum(col[:-1]) == col[-1], 'col {}'.format(c) 

the caveat (and reason left original intact) might explode average junior high brain. use caution.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -