Calculating the totals of odd and even numbers from a file in Python
Question: 
    def main():
    
        infile = open('numbers.txt','r')
    
        evenTotal = 0
        oddTotal = 0
    
        line = infile.readline()
    
        while line != '':
            total += int(line)
            line = infile.readline()
    
        print('The total for the even numbers is',evenTotal)
        print('The total for the odd numbers is',oddTotal)
    
        infile.close()
        print('All done!')
    
    main()
    

I trying to make it so that the program reads the numbers from a file in its
directory and then separates, calculates and displays the total of the two
sets. The thing I am having trouble with is the part in the middle with the
identification of the odds and the evens. I do know that the while loop I have
written in the middle calculates the total but I don't know how to modify it
to make it so it does what I want it to do.


Answer: from itertools you can use the partition recipe to partition into even and odd
and return the sum of those

    
    
    from itertools import ifilterfalse,imap,ifilter,tee
    def partition(pred, iterable):
        'Use a predicate to partition entries into false entries and true entries'
        # partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
        t1, t2 = tee(iterable)
        return ifilterfalse(pred, t1), ifilter(pred, t2)
    
    def is_odd(x):
        return bool(x%2)
    
    list_of_ints = imap(int,filter(lambda x:x.strip().isdigit(),infile))
    odds, evens= partition(is_odd,list_of_ints)
    print sum(evens),sum(odds) 
    

it will likely be a little bit slower than freddies answer ... but it is a
good pattern to know

or as @JonClements [pointed
out](http://chat.stackoverflow.com/transcript/message/21653318#21653318) in
chat

    
    
    r = range(11)
    d = dict.fromkeys([0, 1], 0)
    for i in r: d[i % 2] += i
    

is a neat way to do it

