Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Summation of consecutive elements power
When it is required to add the consecutive elements power, an 'if' condition and a simple iteration along with the '**' operator are used. This technique calculates the sum of each element raised to the power of its consecutive frequency count.
Example
Below is a demonstration of the same ?
my_list = [21, 21, 23, 23, 45, 45, 45, 56, 56, 67]
print("The list is :")
print(my_list)
my_freq = 1
my_result = 0
for index in range(0, len(my_list) - 1):
if my_list[index] != my_list[index + 1]:
my_result = my_result + my_list[index] ** my_freq
my_freq = 1
else:
my_freq += 1
my_result = my_result + my_list[len(my_list) - 1] ** my_freq
print("The resultant value is :")
print(my_result)
Output
The list is : [21, 21, 23, 23, 45, 45, 45, 56, 56, 67] The resultant value is : 95298
How It Works
Let's break down how the calculation works for each group of consecutive elements:
21 appears 2 times consecutively: 212 = 441
23 appears 2 times consecutively: 232 = 529
45 appears 3 times consecutively: 453 = 91,125
56 appears 2 times consecutively: 562 = 3,136
67 appears 1 time: 671 = 67
Total: 441 + 529 + 91,125 + 3,136 + 67 = 95,298
Step-by-Step Explanation
A list is defined and is displayed on the console.
An integer for frequency and result are defined.
The list is iterated over, and an 'if' condition is placed.
It checks to see if consecutive elements are equal or not.
If they are not equal, the element is raised to the power of its frequency and added to the result variable.
The frequency variable is re-initialized to 1.
Otherwise, the frequency variable is incremented by 1.
After the loop, the last element is processed separately to handle the final group.
This result variable is the output that is displayed on the console.
Alternative Approach Using groupby
You can also solve this problem using Python's itertools.groupby() for a more concise solution ?
from itertools import groupby
my_list = [21, 21, 23, 23, 45, 45, 45, 56, 56, 67]
print("The list is :")
print(my_list)
my_result = sum(key ** len(list(group)) for key, group in groupby(my_list))
print("The resultant value is :")
print(my_result)
The list is : [21, 21, 23, 23, 45, 45, 45, 56, 56, 67] The resultant value is : 95298
Conclusion
This technique efficiently calculates the sum of consecutive elements raised to their frequency power. The manual approach gives you full control over the iteration, while groupby() provides a more Pythonic and concise solution.
