3

So the following code reads through two text files both containing 25 ints on 25 lines and puts them in two respective lists:

num_DIR = '/path/to/num.txt'
den_DIR = '/path/to/den.txt'

def makeList(DIR):
    list = []
    for line in open(DIR).readlines():
            list.append(line.strip())
    return list

num_list = makeList(num_DIR)
den_list = makeList(den_DIR)

Outputting:

num_list = ['76539', '100441', '108637', '108874', '103580', '91869', '78458', '61955', '46100', '32701', '21111', '13577', '7747', '4455', '2309', '1192', '554', '264', '134', '63', '28', '15', '12', '7', '5']

den_list = ['621266', '496647', '436229', '394595', '353249', '305882', '253983', '199455', '147380', '102872', '67255', '41934', '24506', '13778', '7179', '3646', '1778', '816', '436', '217', '114', '74', '49', '44', '26']

How would I go about making each value in both lists the added sum of all the value after it, as in an accumulation list?

Sean
  • 1,283
  • 9
  • 27
  • 43

3 Answers3

4

You can also use sum and a list comprehension if performance is not critical:

>>> num_list=[1,2,3]
>>> [sum(num_list[:y]) for y in range(1, len(num_list) + 1)]
[1, 3, 6]
timgeb
  • 76,762
  • 20
  • 123
  • 145
4

You seem to want the sum of all values to the end of the list after each element

summed=[]
den_list = map(int,den_list)
for i,j in enumerate(den_list[:-1]):
    summed += j,sum(den_list[i+1:])

If you don't want to keep the original values in the list

summed=[sum(num_list[i+1:])for i,j in enumerate(num_list[:-1])]
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
3

If you are running python 3.2 or later, batteries are included in itertools.accumulate.

If you're running a version prior to that, the pure-python equivalent provided in the docs works equivalently (albeit not at C speed):

def accumulate(iterable, func=operator.add):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = next(it)
    yield total
    for element in it:
        total = func(total, element)
        yield total

demo:

from itertools import accumulate

list(accumulate(map(int,num_list)))
Out[3]: 
[76539,
 176980,
 285617,
 394491,
 498071,
 589940,
 668398,
 730353,
 776453,
 809154,
 830265,
 843842,
 #snip...,
 860627
]

Note that you'll need to turn all those strings into ints, as I did with map.

roippi
  • 25,533
  • 4
  • 48
  • 73