Question

I have looked around but have been unable to find out why my code is failing, and how to do it right. I'm new (3 days) to coding, so forgive my noobishness.

I start with a list of integers, and essentially I want to make a new or updated list where the new list's first index has a value = the sum of the first 10 values of the original list (0-10), and then the new list's second index has a value = the sum of the original list's (1-11) index values.

The problem is that it adds everything incorrectly, and in a manner such that I have not yet been able to figure out the pattern.

Here's what I have:

def sum_range(filename, grouping = 10):
    """sums up the ss values for 'groupings' numbers of indices.
    Shows ALL results, regardless of how high or low strandedness is"""

    sslist = ssc_only(filename)
    # "ssc_only(filename)" takes my input and returns it as a list of int,
    # which I want to use for this function

    sslist = [sum(sslist[i:i+grouping]) for i in sslist]

    return sslist
Was it helpful?

Solution

I think you probably want for i in range(len(sslist)) (use xrange instead of range in python 2 if you're concerned about memory consumption).

lstlen=len(sslist)
sslist = [sum(sslist[i:min(i+grouping,lstlen)]) for i in range(lstlen)]

You are looping over list items instead of over list indices

Of course, your last 10 elements will be the sum of less than 10 elements. As I don't know what you want to do with those elements, I'll leave it to you to figure out what you want to do with them.

OTHER TIPS

Don't think your summing is right ... also if you're making groups of 10, you'll get 10 less samples than in the original list - this give len(r) - 10 in the expression below.

>>> r = range(20)
>>> r
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> [sum(r[n:10+n]) for n in range(len(r)-10)]
[45, 55, 65, 75, 85, 95, 105, 115, 125, 135]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top