从字符串计算算术运算的Python程序
给定一个带有元素乘法的字符串,转换为这些乘法的总和。
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.
方法 1:使用 map() + mul + sum() + split()
以上功能的组合可以解决这个问题。在这里,我们使用 sum() 执行求和,使用 mul() 执行乘法,split() 用于拆分元素以创建乘法操作数。 map() 用于将逻辑扩展到每个计算的乘法。
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))
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))
输出
The original string is : 5x6, 9x10, 7x8
The computed summation of products : 176
方法 2:使用 eval() + replace()
在此,我们将乘法符号转换为乘法运算符(' * '),类似地,将逗号符号转换为算术“ + ”符号。然后 eval() 执行内部计算并返回结果。
蟒蛇3
# 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))
输出
The original string is : 5x6, 9x10, 7x8
The computed summation of products : 176