Help with cumulative sum

MRAB python at mrabarnett.plus.com
Tue Sep 8 22:33:31 CEST 2009


Maggie wrote:
> On Sep 8, 4:17 pm, MRAB <pyt... at mrabarnett.plus.com> wrote:
>> Maggie wrote:
>>> On Sep 8, 3:29 pm, Maggie <la.f... at gmail.com> wrote:
>>>> Building on the code that I posted in one of the previous posts.. I
>>>> need to find a cumulative sum of the file of the times in the test
>>>> file:
>>>> here is the code i have:
>>>> #!/usr/bin/python
>>>> import os.path
>>>> #name of output file
>>>> filename = "OUTPUT.txt"
>>>> #open the file
>>>> test = open ("test.txt", "rU")
>>>> #read in all the data into a list
>>>> readData = test.readlines()
>>>> count = 0
>>>> FILE = open(filename, "w")
>>>> for item in readData:
>>>>    count = count + 1
>>>>    tmp_string = str(count) + '  ' + item
>>>>    print >> FILE, tmp_string,
>>>> else:
>>>>    print 'The loop is finito'
>>>> -----
>>>> my test file is this
>>>> 23
>>>> 241
>>>> 34234
>>>> 83
>>>> 123
>>>> and I need to find a CUMULATIVE sum (or the running sum)...what would
>>>> be the best way to go about that given the code i already have?
>>>> thank you all!
>>> ---
>>> was trying to plug in the sum for the loop..but for some reason it
>>> doesnt want to work --
>> Read the traceback.
>>
>>
>>
>>> #!/usr/bin/python
>>> import os.path
>>> #name of output file
>>> filename = "OUTPUT.txt"
>>> #open the file
>>> formisano = open ("test.txt", "rU")
>>> #read in all the data into a list
>>> readData = formisano.readlines()
>>> sum = 0
>> Try to avoid using the names of builtin functions and classes, in this
>> case 'sum'.
>>
>>> count = 0
>>> FILE = open(filename, "w")
>>> for item in readData:
>>>    count = count + 1
>>>    sum = sum + (int(item) * int(item))
>>>    tmp_string = str(count) + '     ' + item + '    '+ sum
>> You can't add a number to a string; a number is a number and a string is
>> a string! :-)
>>
>>      tmp_string = str(count) + '        ' + item + '    '+ str(sum)
>>
>>>    print >> FILE, tmp_string,
>>> else:
>>>    print 'The loop is finito'
>>
> 
> I saw my mistake...now it is telling me the following --
> 
> Traceback (most recent call last):
>   File "formisano_count.py", line 22, in <module>
>     running_sum = running_sum + (int(item) * int(item))
> ValueError: invalid literal for int() with base 10: ''
> ..
> not sure what exactly i am doing wrong!

You're trying to convert an empty string into an integer. Does the file
contain a blank line?



More information about the Python-list mailing list