Open In App

Python program to compute arithmetic operation from String

Improve
Improve
Like Article
Like
Save
Share
Report

Given a String with the multiplication of elements, convert to the summation of these multiplications. 

Input : test_str = ‘5×10, 9×10, 7×8’ 
Output : 196 
Explanation : 50 + 90 + 56 = 196.

Input : test_str = ‘5×10, 9×10’ 
Output : 140 
Explanation : 50 + 90 = 140. 
 

Method 1 : Using map() + mul + sum() + split()

The combination of the above functions can be used to solve this problem. In this, we perform summation using sum() and multiplication using mul(), split() is used to split elements for creating operands for multiplication. The map() is used to extend the logic to multiplication to each computation.

Python3




# importing module
from operator import mul
 
# initializing string
test_str = '5x6, 9x10, 7x8'
 
# printing original string
print("The original string is : " + str(test_str))
 
# sum() is used to sum the product of each computation
res = sum(mul(*map(int, ele.split('x'))) for ele in test_str.split(', '))
 
# printing result
print("The computed summation of products : " + str(res))


Output

The original string is : 5x6, 9x10, 7x8
The computed summation of products : 176

Time Complexity: O(n)

Auxiliary Space: O(n)

Method 2 : Using eval() + replace()

In this, we convert the multiplication symbol to the operator for multiplication(‘*‘), similarly, comma symbol is converted to arithmetic “+” symbol. Then eval() performs internal computations and returns the result.

Python3




# initializing string
test_str = '5x6, 9x10, 7x8'
 
# printing original string
print("The original string is : " + str(test_str))
 
# using replace() to create eval friendly string
temp = test_str.replace(',', '+').replace('x', '*')
 
# using eval() to get the required result
res = eval(temp)
 
# printing result
print("The computed summation of products : " + str(res))


Output

The original string is : 5x6, 9x10, 7x8
The computed summation of products : 176

Time Complexity: O(n) -> replace function takes O(n)

Auxiliary Space: O(n)

Approach#3: Using split(): This approach uses a loop and string splitting to compute the arithmetic operations in the input string. It splits the input string using the “,” separator and then uses another split operation to separate the operands of each arithmetic operation. Finally, it multiplies the operands and adds the result to a running total. The function returns the final sum.

  1. Initialize a variable result to 0 to store the sum of all the arithmetic operations.
  2. Split the string input using the “,” separator and store it in the variable arr.
  3. Iterate over the array arr and for each element perform the following operations:
    • Split the element using the “x” separator and store it in the variables a and b.
    • Convert both variables a and b to integer using int() function.
    • Compute the product of a and b.
    • Add the result to the variable result.
  4. Return the final result.

Python3




# Function to compute the arithemetic
# operations
def compute_arithmetic_operation(test_str):
    result = 0
    arr = test_str.split(", ")
    for element in arr:
        a, b = element.split("x")
        result += int(a) * int(b)
    return result
 
# Driver Code
test_str = '5x6, 9x10, 7x8'
print(compute_arithmetic_operation(test_str))


Output

176

Time Complexity: O(n), where n is the number of arithmetic operations in the input string.
Space Complexity: O(1), as we are not using any extra data structure to store the intermediate results.

Approach 4 : Using List Comprehension and reduce() function

step-by-step approach

Initialize a string variable test_str with the value ‘5×6, 9×10, 7×8’.
Print the original string using the print() function and string concatenation.
Split the string by comma , using the split() method, which returns a list of substrings. Each substring represents a pair of numbers separated by the letter ‘x’.
Apply a list comprehension to the list of substrings to split each substring by ‘x’ and get two numbers as separate elements of a list.
Use the multiplication operation * to multiply the two numbers together and generate a list of products.
Use the functools.reduce() function to add all the products together and get the required result.
Print the computed summation of products using the print() function and string concatenation.

Python3




import functools
 
# initializing string
test_str = '5x6, 9x10, 7x8'
 
# printing original string
print("The original string is : " + str(test_str))
 
# using list comprehension to get list of products
products = [int(x) * int(y) for x, y in [pair.split('x') for pair in test_str.split(',')]]
 
# using reduce() to get the required result
res = functools.reduce(lambda x, y: x + y, products)
 
# printing result
print("The computed summation of products : " + str(res))


Output

The original string is : 5x6, 9x10, 7x8
The computed summation of products : 176

Time complexity: O(n), where n is the length of the input string.

Auxiliary space: O(n), where n is the length of the input string.



Last Updated : 22 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads