Reputation: 1
I have been fiddling round with this code for ages and cannot figure out how to make it pass the doctests. the output is always 1000 less than the corrects answer. is there a simple way to change this code so that it gives the desired output ?? my code is:
def sum_numbers_in_file(filename):
"""
Return the sum of the numbers in the given file (which only contains
integers separated by whitespace).
>>> sum_numbers_in_file("numb.txt")
19138
"""
f = open(filename)
m = f.readline()
n = sum([sum([int(x) for x in line.split()]) for line in f])
f.close()
return n
the values in the file are:
1000
15000
2000
1138
Upvotes: 0
Views: 5352
Reputation: 879739
You could use two for
-loops in one generator expression:
def sum_numbers_in_file(filename):
"""
Return the sum of the numbers in the given file (which only contains
integers separated by whitespace).
>>> sum_numbers_in_file("numb.txt")
19138
"""
with open(filename) as f:
return sum(int(x)
for line in f
for x in line.split())
The generator expression above is equivalent to
result = []
for line in f:
for x in line.split():
result.append(int(x))
return sum(result)
Upvotes: 1
Reputation: 27747
You pull out the first line and store it in m. Then never use it.
Upvotes: 1
Reputation: 99640
The culprit is:
m = f.readline()
when you are doing f.readline()
, it is losing the 1000, which is not being considered in the list comprehension. Hence the error.
This should work:
def sum_numbers_in_file(filename):
"""
Return the sum of the numbers in the given file (which only contains
integers separated by whitespace).
>>> sum_numbers_in_file("numb.txt")
19138
"""
f = open(filename, 'r+')
m = f.readlines()
n = sum([sum([int(x) for x in line.split()]) for line in m])
f.close()
return n
Upvotes: 3