Open In App

Python | Summation of Non-Zero groups

Improve
Improve
Like Article
Like
Save
Share
Report

Many times we need to get the summation of not the whole list but just a part of it and at regular intervals. These intervals are sometimes decided statically before traversal, but sometimes, the constraint is more dynamic and hence we require to handle it in more complex way. Criteria discussed here is summation of non-zero groups. Let’s discuss certain ways in which this task can be done. 

Method #1 : Using loops This task can be performed using the brute force manner using the loops. We just traverse the list each element to test for it’s succeeding element to be non-zero value and perform the summation once we find a next value to be zero and append it in result list. 

Python3




# Python3 code to demonstrate
# summation of non-zero groups
# Using loops
 
# initializing list
test_list = [4, 9, 0, 0, 3, 4, 5, 0, 0, 4, 0]
 
# printing original list
print("The original list : " + str(test_list))
 
# using loops
# summation of non-zero groups
res = []
val = 0
for ele in test_list:
    if ele == 0:
        if val != 0:
            res.append(val)
            val = 0
    else:
        val += ele
 
# print result
print("The non-zero group summation of list is : " + str(res))


Output : 

The original list : [4, 9, 0, 0, 3, 4, 5, 0, 0, 4, 0]
The non-zero group summation of list is : [13, 12, 4]

Time complexity: O(n), where n is the length of the test_list. The loop  takes O(n) time
Auxiliary Space: O(n), where n is the number of elements in the list test_list

  Method #2 : Using itertools.groupby() + sum() This particular task can also be performed using groupby function to group all the non-zero values and sum function can be used to perform their summation. 

Python3




# Python3 code to demonstrate
# summation of non-zero groups
# Using itertools.groupby() + sum()
from itertools import groupby
 
# initializing list
test_list = [4, 9, 0, 0, 3, 4, 5, 0, 0, 4, 0]
 
# printing original list
print("The original list : " + str(test_list))
 
# using itertools.groupby() + sum()
# summation of non-zero groups
res = [sum(val) for keys, val in groupby(test_list,
              key = lambda x: x != 0) if keys != 0]
 
# print result
print("The non-zero group summation of list is : " + str(res))


Output : 

The original list : [4, 9, 0, 0, 3, 4, 5, 0, 0, 4, 0]
The non-zero group summation of list is : [13, 12, 4]

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(k), where k is the number of non-zero groups in the input list. 

Method #3 :  Using a generator function

This approach involves defining a generator function that yields the sum of the non-zero groups in the list as it iterates through the list. This approach can be more efficient in terms of memory usage compared to the other approaches, as the result list does not need to be stored in memory.

Python3




# Initialize the list
test_list = [4, 9, 0, 0, 3, 4, 5, 0, 0, 4, 0]
 
# Print the original list
print("The original list:", test_list)
 
# Define a generator function to sum the non-zero groups
def sum_non_zero_groups(lst):
    val = 0
    for ele in lst:
        if ele == 0:
            if val != 0:
                yield val
                val = 0
        else:
            val += ele
 
# Sum the non-zero groups using the generator function
res = list(sum_non_zero_groups(test_list))
 
# Print the result
print("The non-zero group summation:", res)
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original list: [4, 9, 0, 0, 3, 4, 5, 0, 0, 4, 0]
The non-zero group summation: [13, 12, 4]

Time complexity: O(n)

Auxiliary space: O(n) to store final result

Python3




# Python3 code to demonstrate
# summation of non-zero groups
# Using list comprehension
 
# initializing list
test_list = [4, 9, 0, 0, 3, 4, 5, 0, 0, 4, 0]
 
# printing original list
print("The original list : " + str(test_list))
 
# using list comprehension
# summation of non-zero groups
res = [sum(group) for zero, group in itertools.groupby(test_list) if zero != 0]
 
# print result
print("The non-zero group summation of list is : " + str(res))


Method #4 : Using numpy.where() + numpy.sum()

 Here’s a step-by-step breakdown of the algorithm:

Initialize a list test_list with some elements.
Print the original list using the print() function.
Convert the list to a NumPy array using np.array() function and store it in a variable arr.
Use np.where() function to get the indices of all occurrences of 0 in the array arr and store it in a variable idx.
Using np.insert() and np.append() functions, add -1 at the beginning of idx and the length of the array arr at the end of idx to include the first and last groups of non-zero numbers in the summation.
Use a list comprehension with the zip() function to iterate over the pairs of indices (start, end) that define the non-zero groups in arr. The first pair (start, end) will be (0, idx[0]), the last pair will be (idx[-1] + 1, len(arr)), and the pairs in between will be (idx[i-1] + 1, idx[i]) for i in range(1, len(idx)).
For each pair (start, end), compute the summation of the corresponding group of non-zero numbers using the np.sum() function and store it in a list res

Python3




#initializing list
test_list = [4, 9, 0, 0, 3, 4, 5, 0, 0, 4, 0]
 
#printing original list
print("The original list : " + str(test_list))
 
#using numpy.where() + numpy.sum()
#summation of non-zero groups
arr = np.array(test_list)
idx = np.where(arr == 0)[0]
res = [np.sum(arr[start:end]) for start, end in zip(np.insert(idx, 0, -1) + 1, np.append(idx, len(arr))) if start != end]
 
#print result
print("The non-zero group summation of list is : " + str(res))


Output:
The original list : [4, 9, 0, 0, 3, 4, 5, 0, 0, 4, 0]
The non-zero group summation of list is : [13, 12, 4]

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the number of elements in the input list. This is because we are creating a new numpy array to store the input list, and also using a list to store the final result.



Last Updated : 05 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads