Open In App

Python – Maximum Pair Summation in numeric String

Last Updated : 10 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, we might have a problem in which we require to get the maximum summation of 2 numbers from Strings but with a constraint of having the numbers in successions. This type of problem can occur while competitive programming. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using max() + zip() + list comprehension This problem can be solved using the combination of above three function in which max function can be used to get the max value, zip and list comprehension doing the task of extending the logic to the whole list. 

Step-by-step approach:

  1. Initialize the test_string variable with a string of digits.
  2. Print the original string using the print() function.
  3. Convert the test_string to a list of individual digits using the list() function.
  4. Use list comprehension with zip() function to iterate over the test_string and its sliced version (with one position shift), such that each element of the sliced string is paired with the element in the corresponding position in the original string.
  5. In each iteration, convert the two digits to integers, add them and return the sum.
  6. Use the max() function to get the maximum sum of consecutive pairs of digits obtained in step 4.
  7. Print the result obtained in step 6 using the print() function.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate
# Maximum Pair Summation in String
# using zip() + max() + list comprehension
 
# initializing string
test_string = '6543452345456987653234'
 
# printing original string
print("The original string : " + str(test_string))
 
# using zip() + max() + list comprehension
# Maximum Pair Summation in String
test_string = list(test_string)
res = max(int(a) + int(b) for a, b in zip(test_string, test_string[1:]))
 
# print result
print("The maximum consecutive sum is : " + str(res))


Output : 

The original string : 6543452345456987653234
The maximum consecutive sum is : 17

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2 : Using max() + map() + operator.add The above problem can also be solved using yet another combination of functions. In this combination, map functions performs the task of extending the logic to whole list and add operator is used to perform the addition. 

Python3




# Python3 code to demonstrate
# Maximum Pair Summation in String
# using max() + map() + operator.add
from operator import add
 
# initializing string
test_string = '6543452345456987653234'
 
# printing original string
print("The original string : " + str(test_string))
 
# using max() + map() + operator.add
# Maximum Pair Summation in String
res = max(map(add, map(int, test_string), map(int, test_string[1:])))
 
# print result
print("The maximum consecutive sum is : " + str(res))


Output : 

The original string : 6543452345456987653234
The maximum consecutive sum is : 17

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 3: “Maximum Pair Summation in String using iteration”.

One approach to solve the problem of finding the maximum consecutive sum in a string can be done by iterating over the string and comparing the current sum with the maximum sum seen so far.

Step-by-step approach:

  • Initialize two variables res and cur_sum to zero.
  • Iterate over the string using a for loop and range(n-1) to access consecutive pairs of characters in the string.
  • Convert the consecutive pairs of characters to integers using int() function and add them to get the current sum.
  • Find the maximum of the current sum and the previous maximum sum seen so far using max() function and update the result variable res.
  • After the loop, the value of res variable will hold the maximum consecutive sum in the string.
  • Print the maximum consecutive sum using the print() function.

Python3




# Python3 code to demonstrate
# Maximum Pair Summation in String
# using iteration
 
# initializing string
test_string = '6543452345456987653234'
 
# printing original string
print("The original string : " + str(test_string))
 
# using iteration
n = len(test_string)
res = 0
cur_sum = 0
for i in range(n-1):
    cur_sum = int(test_string[i]) + int(test_string[i+1])
    res = max(res, cur_sum)
 
# print result
print("The maximum consecutive sum is : " + str(res))


Output

The original string : 6543452345456987653234
The maximum consecutive sum is : 17

Time complexity: O(n), where n is the length of the input string
Auxiliary space: O(1) – constant space

Method 4: Using a while loop

Step-by-step approach:

  1. Compute the length of the string using the len() function and store it in the variable n.
  2. Initialize the variables res, cur_sum, and i to 0.
  3. Enter a while loop that continues as long as i is less than n-1.
  4. Within the loop, compute the current pair summation by adding the current character and the next character together using the int() function to convert them to integers.
  5. Update the maximum sum so far using the max() function to compare res and cur_sum.
  6. Increment i by 1 to move on to the next pair of characters.
  7. When the loop finishes, print the maximum sum using the print() function and string concatenation operator +.

Python3




# Python3 code to demonstrate
# Maximum Pair Summation in String
# using a while loop
 
# initializing string
test_string = '6543452345456987653234'
 
# printing original string
print("The original string : " + str(test_string))
 
# using a while loop
n = len(test_string)
res = 0
cur_sum = 0
i = 0
while i < n-1:
    cur_sum = int(test_string[i]) + int(test_string[i+1])
    res = max(res, cur_sum)
    i += 1
 
# print result
print("The maximum consecutive sum is : " + str(res))


Output

The original string : 6543452345456987653234
The maximum consecutive sum is : 17

Time complexity: O(n), where n is the length of the input string, since we need to iterate over the string once to compute the maximum pair summation.
Auxiliary space: O(1), as we are only using a constant amount of extra space for storing the variables (res, cur_sum, and i). This means that the space required by the algorithm does not depend on the size of the input string.

Method 5: Using list comprehension and slicing

This method involves using a list comprehension and slicing to iterate through the string and calculate the maximum consecutive sum.

Step-by-step approach:

  1. Initialize the string
  2. Use list comprehension and slicing to create a list of consecutive pairs of characters in the string.
  3. Use a lambda function and map to convert each pair of characters to their sum.
  4. Use the built-in max() function to find the maximum consecutive sum in the list.
  5. Print the result.

Python3




# Python3 code to demonstrate
# Maximum Pair Summation in String
# using list comprehension and slicing
 
# initializing string
test_string = '6543452345456987653234'
 
# printing original string
print("The original string : " + str(test_string))
 
# using list comprehension and slicing
pairs = [test_string[i:i+2] for i in range(len(test_string)-1)]
pair_sums = list(map(lambda x: int(x[0])+int(x[1]), pairs))
res = max(pair_sums)
 
# print result
print("The maximum consecutive sum is : " + str(res))


Output

The original string : 6543452345456987653234
The maximum consecutive sum is : 17

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), as a list of length n/2 is created.



Similar Reads

Convert Factor to Numeric and Numeric to Factor in R Programming
Factors are data structures that are implemented to categorize the data or represent categorical data and store it on multiple levels. They can be stored as integers with a corresponding label to every unique integer. Though factors may look similar to character vectors, they are integers, and care must be taken while using them as strings. The fac
5 min read
Python - Numeric Sort in Mixed Pair String List
Sometimes, while working with data records, we can have a problem in which we receive data in custom format, and we need to perform a sort. We can receive both name of person and space-separated score and require to get the best to worst sorting. Lets discuss a way in which this particular problem can be solved. Method #1 : Using split() + sort() +
5 min read
Python | Pair summation of list elements
Sometimes, while working with Python list, one can have a problem in which one needs to find perform the summation of list in pair form. This is useful as a subproblem solution of bigger problem in web development and day-day programming. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loop This is the brute force
4 min read
Python Regex to extract maximum numeric value from a string
Given an alphanumeric string, extract maximum numeric value from that string. Alphabets will only be in lower case. Examples: Input : 100klh564abc365bgOutput : 564Maximum numeric value among 100, 564 and 365 is 564.Input : abchsd0sdhsOutput : 0Python Regex to extract maximum numeric value from a stringThis problem has existing solution please refer
2 min read
Python - Summation of float string list
Sometimes, while working with Python list, we can have a problem in which we need to find summation in list. But sometimes, we don’t have a natural number but a floating-point number in string format. This problem can occur while working with data, both in web development and Data Science domain. Let’s discuss the ways in which this problem can be
7 min read
Python - Get summation of numbers in string list
Sometimes, while working with data, we can have a problem in which we receive series of lists with data in string format, which we wish to accumulate as list. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + int() This is the brute force method to perform this task. In this, we run a loop for entire list, con
3 min read
Python | Embedded Numbers Summation in String List
Sometimes, while working with Python lists, we can have problem in which we need to concatenate embedded numbers in Strings list and perform its summation. This can have application in domains dealing with data. Lets discuss certain ways in which this task can be performed. Method #1 : Using join() + loop The combination of above functionalities ca
6 min read
Python - Dictionary values String Length Summation
Sometimes, while working with Python dictionaries we can have problem in which we need to perform the summation of all the string lengths which as present as dictionary values. This can have application in many domains such as web development and day-day programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using s
4 min read
Python | Ways to remove numeric digits from given string
Given a string (may contain both characters and digits), write a Python program to remove the numeric digits from string. Let's discuss the different ways we can achieve this task. Method #1: Using join and isdigit() C/C++ Code # Python code to demonstrate # how to remove numeric digits from string # using join and isdigit # initialising string ini
6 min read
Python | Get the numeric prefix of given string
Given a string. the task is to print numeric prefix in string (if it is present in string). Given below are few methods to solve the task. Method #1: Using Naive Method C/C++ Code # Python code to demonstrate # to get numeric prefix in string # if present # initialising string ini_string = &amp;quot;123abcjw&amp;quot; ini_string2 = &amp;quot;abcedd
5 min read
Practice Tags :