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
Python - Convert Alternate String Character to Integer
Interconversion between data types is facilitated by python libraries quite easily. But the problem of converting the alternate list of string to integers is quite common in development domain. Letâs discuss few ways to solve this particular problem. Method #1 : Naive Method This is most generic met
5 min read
Python program to Increment Suffix Number in String
Given a String, the task is to write a Python program to increment the number which is at end of the string. Input : test_str = 'geeks006' Output : geeks7 Explanation : Suffix 006 incremented to 7. Input : test_str = 'geeks007' Output : geeks8 Explanation : Suffix 007 incremented to 8. Method #1 : U
5 min read
Python program to convert hex string to decimal
Converting a hexadecimal string to a decimal number is a common task in programming, especially when working with binary data or low-level computations. Hexadecimal values offer a concise way to represent large numbers.Using the int() FunctionUsing the int() function is the most common and straightf
2 min read
Python Program to move numbers to the end of the string
Given a string, the task is to write a Python program to move all the numbers in it to its end. Examples: Input : test_str = 'geek2eeks4g1eek5sbest6forall9' Output : geekeeksgeeksbestforall241569 Explanation : All numbers are moved to end. Input : test_str = 'geekeeksg1eek5sbest6forall9' Output : ge
6 min read
Python program to convert POS to SOP
Write a program in Python to convert standard POS(product of sums) form to standard SOP(sum of products) form. Assumptions: The input POS expression is standard. The variables in POS expression are continuous i.e. if expression contains variable A then it will have variables B, C respectively and ea
4 min read
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
Output of Python Programs | Set 19 (Strings)
1) What is the output of the following program? PYTHON3 str1 = '{2}, {1} and {0}'.format('a', 'b', 'c') str2 = '{0}{1}{0}'.format('abra', 'cad') print(str1, str2) a) c, b and a abracad0 b) a, b and c abracadabra c) a, b and c abracadcad d) c, b and a abracadabra Ans. (d) Explanation: String function
3 min read
Python program to convert int to exponential
Given a number of int type, the task is to write a Python program to convert it to exponential. Examples: Input: 19 Output: 1.900000e+01 Input: 2002 Output: 2.002000e+03 Input: 110102 Output: 1.101020e+05Approach: We will first declare and initialise an integer numberThen we will use format method t
1 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