Sum of all numbers in a file

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

Answers


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

You pull out the first line and store it in m. Then never use it.


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)

Need Your Help

Rails3 ActiveResource Post Call delivers an empty Parameter Hash

ruby-on-rails-3 post sinatra params activeresource

I am trying to create a new "Person" in a Sinatra API app from a Rails3 app using ActiveResource and Json. In Rails3, I created a "Person" model and using ActiveResource I correctly call the API, ...

login function rendering first letter only

php function session login user

I have just made the login function and it is working alright;

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.