[Tutor] summer_v04.py
Kent Johnson
kent37 at tds.net
Wed Feb 21 14:14:14 CET 2007
Christopher Spears wrote:
> I've been working on a version of a script I found in
> "Programming Python". The helpful users of this forum
> gave me some advice to make the code less wordy. Here
> is the code:
>
> #!/usr/bin/python
> import string
>
> def find_longest_line(fileName):
> line_list = [line.split() for line in open(fileName,
> 'r').readlines()]
> numCols = max(len(cols) for cols in line_list)
> #print numCols
> return numCols
>
> def summer(fileName):
> length_longest_col = find_longest_line(fileName)
> sums = [0] * length_longest_col
> for line in line_list:
> cols = string.split(line)
> for i in range(len(cols)):
> sums[i] = sums[i] + float(cols[i])
> return sums
>
> if __name__ == '__main__':
> import sys
> print summer(sys.argv[1])
> #print find_longest_line(sys.argv[1])
>
> The code opens a 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
>
> Then the script adds the columns in the file together.
>
> However, when I run the script, I get a syntax error:
When you fix the syntax error, which others have shown how to do, you
will get a NameError in summer() because the name line_list is private
to find_longest_line(). The simplest way to fix this would be to combine
find_longest_line() and summer() or to read the file lines in summer()
and pass line_list, instead of the file name, to find_longest_line().
Kent
More information about the Tutor
mailing list