Python | Interval List Summation
Last Updated :
07 May, 2023
There are numerous ways to initialize the list with the elements, but sometimes, its required to initialize the lists with the numbers in a sliced way and find its summation. This can be custom and hence knowledge of this can come handy. Let’s discuss certain ways in which this can be done.
Method #1 : Using list comprehension + enumerate() + sum() The list comprehension can do the possible iteration part and enumerate can help in the part of logic and checking for the valid elements required in the list. The sum() is used to perform summation.
Python3
test_list = list ( range ( 50 ))
print ("The original list is : " + str (test_list))
N = 5
K = 15
res = sum ([i for j, i in enumerate (test_list) if j % K < N ])
print ("The modified range sum list : " + str (res))
|
Output :
The original list is : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49] The modified range sum list : 490
Time Complexity: O(n) where n is the number of elements in the list “test_list”. The list comprehension + enumerate() + sum() is used to perform the task and it takes O(n) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”.
Method #2 : Using itertools.compress() + itertools.cycle() + sum() The above two function can combine to facilitate the solution of the discussed problem. The cycle function can to the task of repetition and the compress function can be beneficial when it comes to clubbing the segments together. The sum() is used to perform summation.
Python3
from itertools import compress, cycle
test_list = list ( range ( 50 ))
print ("The original list is : " + str (test_list))
N = 5
K = 15
func = cycle([ True ] * N + [ False ] * (K - N))
res = sum ( list (compress(test_list, func)))
print ("The modified range sum list : " + str (res))
|
Output :
The original list is : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49] The modified range sum list : 490
Time Complexity: O(n*n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), constant extra space is required
Share your thoughts in the comments
Please Login to comment...