Python – Summation of consecutive elements power
Last Updated :
03 May, 2023
Given a List, the task is to write a Python program to compute summation of power of consecutive elements occurrences frequency.
Examples:
Input : test_list = [2, 2, 2, 3, 3, 3, 3, 4, 4, 5]
Output : 110
Explanation : 2^3 + 3^4 + 4^2 + 5 = 110
Input : test_list = [2, 2, 2, 3, 3, 3, 3, 4, 4]
Output : 105
Explanation : 2^3 + 3^4 + 4^2 = 105
Method #1 : Using loop
In this, we iterate for each element and test for next element, if found to be different, perform summation of power of consecutive elements, else add counter to get frequency to raise number to.
Python3
test_list = [ 2 , 2 , 2 , 3 , 3 , 3 , 3 , 4 , 4 , 5 ]
print ( "The original list is : " + str (test_list))
freq = 1
res = 0
for idx in range ( 0 , len (test_list) - 1 ):
if test_list[idx] ! = test_list[idx + 1 ]:
res = res + test_list[idx] * * freq
freq = 1
else :
freq + = 1
res = res + test_list[ len (test_list) - 1 ] * * freq
print ( "Computed summation of powers : " + str (res))
|
Output
The original list is : [2, 2, 2, 3, 3, 3, 3, 4, 4, 5]
Computed summation of powers : 110
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2 : Using defaultdict() + loop + sum()
In this we capture frequency using defaultdict using key value pairs and loop is used to iterate through each element. Next, summation is performed using sum().
Python3
from collections import defaultdict
test_list = [ 2 , 2 , 2 , 3 , 3 , 3 , 3 , 4 , 4 , 5 ]
print ( "The original list is : " + str (test_list))
temp = defaultdict( int )
for ele in test_list:
temp[ele] + = 1
temp = dict (temp)
res = sum ([key * * temp[key] for key in temp])
print ( "Computed summation of powers : " + str (res))
|
Output
The original list is : [2, 2, 2, 3, 3, 3, 3, 4, 4, 5]
Computed summation of powers : 110
Time Complexity: O(n*logn)
Auxiliary Space: O(n)
Method #3: Using Counter object + list comprehension
- Import Counter object from the collections module.
- Initialize the list.
- Get the frequency of each element using the Counter() method and store it in a dictionary.
- Compute the summation using a list comprehension that takes the power of the keys of the dictionary raised to the frequency of each element.
- Print the result.
Python3
from collections import Counter
test_list = [ 2 , 2 , 2 , 3 , 3 , 3 , 3 , 4 , 4 , 5 ]
print ( "The original list is : " + str (test_list))
temp = Counter(test_list)
res = sum ([key * * temp[key] for key in temp])
print ( "Computed summation of powers : " + str (res))
|
Output
The original list is : [2, 2, 2, 3, 3, 3, 3, 4, 4, 5]
Computed summation of powers : 110
Time complexity: O(n)
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...