[Tutor] adding columns of numbers

Christopher Spears cspears2002 at yahoo.com
Fri Feb 2 02:47:43 CET 2007


I've been reading an old copy of "Programming Python"
and started to work on one of its challenges.  I have
a text file called table.txt:

1	5	10	2	1.0
2	10	20	4	2.0	3
3	15	30	8	3	2	1
4	20	40	16	4.0

I want to add each column of numbers, so the end
result would be a list like so:

[10, 50, 100, 30 , 10.0, 5, 1]

So far, I've been able to modify some code I found in
the book:

#!/usr/bin/python
import string

def summer(fileName):
	for lines_in_file in open(fileName, 'r').readlines():
		cols_in_file = string.split(lines_in_file)
		#print cols_in_file
		numCols = len(cols_in_file)
		sums = [0] * numCols
		#print sums
		cols = string.split(lines_in_file)
		#print cols
		for i in range(numCols):
			sums[i] = sums[i] + eval(cols[i])
	return sums
			
if __name__ == '__main__':
	import sys
	print summer(sys.argv[1])

Unfortunately, the output is:
[4, 20, 40, 16, 4.0]

The code can read the file, but the code doesn't sum
the numbers to produce a new list.  Any hints?





More information about the Tutor mailing list