Python program to compute arithmetic operation from String
Last Updated :
22 Apr, 2023
Given a String with the multiplication of elements, convert to the summation of these multiplications.
Input : test_str = '5x10, 9x10, 7x8'
Output : 196
Explanation : 50 + 90 + 56 = 196.
Input : test_str = '5x10, 9x10'
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))
OutputThe 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))
OutputThe 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.
- Initialize a variable result to 0 to store the sum of all the arithmetic operations.
- Split the string input using the "," separator and store it in the variable arr.
- 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.
- 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))
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 '5x6, 9x10, 7x8'.
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))
OutputThe 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.
Similar Reads
Convert String Float to Float List in Python We are given a string float we need to convert that to float of list. For example, s = '1.23 4.56 7.89' we are given a list a we need to convert this to float list so that resultant output should be [1.23, 4.56, 7.89].Using split() and map()By using split() on a string containing float numbers, we c
2 min read
Python - List of float to string conversion When working with lists of floats in Python, we may often need to convert the elements of the list from float to string format. For example, if we have a list of floating-point numbers like [1.23, 4.56, 7.89], converting them to strings allows us to perform string-specific operations or output them
3 min read
Python program to add two Octal numbers Given two octal numbers, the task is to write a Python program to compute their sum. Examples: Input: a = "123", b = "456" Output: 601 Input: a = "654", b = "321" Output: 1175Approach: To add two octal values in python we will first convert them into decimal values then add them and then finally aga
2 min read
Python | Solve given list containing numbers and arithmetic operators Given a list containing numbers and arithmetic operators, the task is to solve the list. Example: Input: lst = [2, '+', 22, '+', 55, '+', 4] Output: 83 Input: lst = [12, '+', 8, '-', 5] Output: 15 Below are some ways to achieve the above tasks. Method #1: Using Iteration We can use iteration as the
3 min read
Check Whether String Contains Only Numbers or Not - Python We are given a string s="12345" we need to check whether the string contains only number or not if the string contains only number we will return True or if the string does contains some other value then we will return False. This article will explore various techniques to check if a string contains
3 min read
Python Program to Find Sum of First and Last Digit Given a positive integer N(at least contain two digits). The task is to write a Python program to add the first and last digits of the given number N. Examples: Input: N = 1247 Output: 8 Explanation: First digit is 1 and Last digit is 7. So, addition of these two (1 + 7) is equal to 8.Input: N = 73
5 min read