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
Selected Reading
Consecutive element maximum product in Python
Python provides several approaches to find the maximum product of two consecutive digits in a string. This is useful when processing numerical data stored as strings and finding optimal adjacent pairs.
Using zip() and max()
We can create pairs of consecutive elements using zip() with list slicing, then find the maximum product ?
number_string = '5238521'
# Given string
print("Given String:", number_string)
# Convert to list for easier processing
digits_list = list(number_string)
print("String converted to list:", digits_list)
# Using zip() to create consecutive pairs and max() to find maximum product
result = max(int(a) * int(b) for a, b in zip(digits_list, digits_list[1:]))
print("The maximum consecutive product is:", result)
Given String: 5238521 String converted to list: ['5', '2', '3', '8', '5', '2', '1'] The maximum consecutive product is: 40
Using map() and operator.mul
The map() function with operator.mul provides a functional programming approach to multiply consecutive pairs ?
from operator import mul
number_string = '5238521'
# Given string
print("Given String:", number_string)
# Convert to list
digits_list = list(number_string)
print("String converted to list:", digits_list)
# Using map() with operator.mul to multiply consecutive pairs
result = max(map(mul, map(int, digits_list), map(int, digits_list[1:])))
print("The maximum consecutive product is:", result)
Given String: 5238521 String converted to list: ['5', '2', '3', '8', '5', '2', '1'] The maximum consecutive product is: 40
Using Simple Loop Approach
A straightforward loop approach that's easy to understand and debug ?
number_string = '5238521'
print("Given String:", number_string)
max_product = 0
for i in range(len(number_string) - 1):
current_product = int(number_string[i]) * int(number_string[i + 1])
max_product = max(max_product, current_product)
print(f"Digits {number_string[i]} × {number_string[i + 1]} = {current_product}")
print("The maximum consecutive product is:", max_product)
Given String: 5238521 Digits 5 × 2 = 10 Digits 2 × 3 = 6 Digits 3 × 8 = 24 Digits 8 × 5 = 40 Digits 5 × 2 = 10 Digits 2 × 1 = 2 The maximum consecutive product is: 40
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
zip() + max()
|
High | Good | Concise, Pythonic code |
map() + operator.mul
|
Medium | Good | Functional programming style |
| Simple loop | High | Good | Debugging and understanding |
Conclusion
The zip() approach offers the most Pythonic solution for finding maximum consecutive products. Use the loop method when you need to see intermediate results or for easier debugging.
Advertisements
