[Tutor] adding columns of numbers

John Fouhy john at fouhy.net
Fri Feb 2 03:10:19 CET 2007


On 02/02/07, Christopher Spears <cspears2002 at yahoo.com> 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
>                 #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]

Compare the output with the input.  Where do you think the output came from?

Can you see how this is reflected in your code?

-- 
John.


More information about the Tutor mailing list