Python program to find the group sum till each K in a list


When it is required to find the group sum till each K in a list, a simple iteration and the ‘append’ method are used.

Example

Below is a demonstration of the same

from collections import defaultdict

my_list = [21, 4, 37, 46, 7, 56, 7, 69, 2, 86, 1]

print("The list is :")
print(my_list)

my_key = 46
print("The key is ")
print(my_key)

my_sum = 0
my_result = []

for ele in my_list:
   if ele != my_key:
      my_sum += ele

   else:
      my_result.append(my_sum)
      my_result.append(ele)
      my_sum = 0

my_result.append(my_sum)

print("The resultant list is :")
print(my_result)

Output

The list is :
[21, 4, 37, 46, 7, 56, 7, 69, 2, 86, 1]
The key is
46
The resultant list is :
[62, 46, 228]

Explanation

  • The required packages are imported into the environment.

  • A list is defined and is displayed on the console.

  • A key is defined and displayed on the console.

  • The sum value is assigned to 0.

  • An empty list is defined.

  • The list is iterated over, and if the element in the list is not equal to the key value, it is added to the sum.

  • Otherwise, the sum and the specific is appended to the empty list.

  • The sum is reinitialized to 0.

  • This sum is finally appended to the empty list.

  • This is displayed as output on the console.

Updated on: 20-Sep-2021

85 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements