[Tutor] adding columns of numbers

Kent Johnson kent37 at tds.net
Fri Feb 2 03:20:00 CET 2007


Christopher Spears wrote:
> 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

This creates a new sums list for each line of the file. You need to 
initialize sums outside the loop. It's a little tricky to figure out how 
long sums really needs to be, since the lines are not all the same length.

> 		#print sums
> 		cols = string.split(lines_in_file)
> 		#print cols
> 		for i in range(numCols):
> 			sums[i] = sums[i] + eval(cols[i])

Instead of eval(cols[i]) it would be better to use float(cols[i]). It's 
usually a good idea to avoid eval().

Extra credit: Write summer() as a one-liner. :-)

(I know, I shouldn't be encouraging this. But it is a good exercise even 
if you wouldn't use it in production code. It would be pretty easy if 
the lines were all the same length...)

Kent

> 	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?
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 




More information about the Tutor mailing list