0

I have a list a=[1,2,3,4,5,6]

I would like to create a function that sums every n elements together in a new list for example

my_sum(a,2)=[3,7,11] - a new list with a[0]+a[1], a[2]+a[3]

my_sum(a,3)=[6,15] - a[0]+a[1]+a[2],

I am stuck, anyone got an idea?

3
  • my_sum(a,4)=[10], if the number beggier then the list, the output would be [] Commented Apr 20, 2020 at 19:30
  • "I am stuck" - did you try anything at all? For example, can you write something that gets the sum for the first n elements? Commented Apr 20, 2020 at 21:53
  • Please don't make more work for others by vandalizing your posts. By posting on the Stack Exchange (SE) network, you've granted a non-revocable right, under a CC BY-SA license, for SE to distribute the content (i.e. regardless of your future choices). By SE policy, the non-vandalized version is distributed. Thus, any vandalism will be reverted. Please see: How does deleting work? …. If permitted to delete, there's a "delete" button below the post, on the left, but it's only in browsers, not the mobile app. Commented Apr 24, 2020 at 21:58

3 Answers 3

2

Try this:

def my_sum(a, n):
    return [sum(a[i: i + n]) if len(a[i: i + n]) >= n else None for i in range(0, len(a), n)]
a=[1,2,3,4,5,6]
my_sum(a, 4)
Sign up to request clarification or add additional context in comments.

Comments

0

Perhaps this is what you're looking for, also quite readable:

def my_sum(array, n):
    result = []
    if n > len(array):
        return []
    for i in range(0, len(array), n):
        result.append(sum(array[i:i+n]))

    return result

ls = [1,2,3,4,5,6]
print(my_sum(ls, 5))

Comments

0

You can try this:

def my_sum(a, b):
    sum = 0
    new_list = []
    lenght = len(a)
    if lenght % b == 0:
        for count, value in enumerate(a):
            if count + 1 == lenght:
                sum += value
                new_list.append(sum)
            elif count != 0 and count % b == 0:
                new_list.append(sum)
                sum = 0
                sum += value
            else:
                sum += value
        return new_list
    else:
        print("It's not possible")
        return

You can do this only If the number of the sum is divisible by the list lenght (this is the reason for the first "If").

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.