NC205328. ArithmeticProblems
描述
输入描述
Each input file only contains one test case.
For each case, each line contains a simple arithmetic expression S (no more than 5× characters) from the different country Praha, which only contains non-negative integers (no more than ), calculating signs (only contains '+', '-', '*', '/') and spaces.
输出描述
For each test case, output the value of the given arithmetic expression (keep 2 decimal places). Especially, in the division operation, if the divisor is 0, output "Cannot be divided by 0"(without quotes) in the single line.
It's guaranteed that the absolute value after each step is always between and .
示例1
输入:
1 + 1 / 1 * 1 - 1
输出:
1.00
示例2
输入:
2/0+0-3*4
输出:
Cannot be divided by 0
pypy3(pypy3.6.1) 解法, 执行用时: 232ms, 内存消耗: 53088K, 提交时间: 2020-06-08 21:27:07
import sys sys.setrecursionlimit(600000) s=input() n=len(s) s=s.replace('+','a') s=s.replace('-','b') s=s.replace('*','c') s=s.replace('/','d') s=s.replace('b','*') s=s.replace('d','+') s=s.replace('a','/') s=s.replace('c','-') try: print('%.2f'%(eval(s))) except: print("Cannot be divided by 0")
Python3(3.5.2) 解法, 执行用时: 436ms, 内存消耗: 26452K, 提交时间: 2020-06-05 16:17:00
import sys sys.setrecursionlimit(1000000) str = input() s = 'x='; for i in str: if i == '-': s += '*' elif i == '/': s += '+' elif i == '+': s += '/' elif i == '*': s += '-' else: s += i try: exec(s) print("%.2f"%x) except: print('Cannot be divided by 0')