列表

详情


NC205328. ArithmeticProblems

描述

During this winter vacation, Little Gyro went for a journey to Praha——a brand new country in the world. After arriving, Little Gyro really found a lot of differences between Praha and our country. One of the differences is based on the maths problems, which often makes Little Gyro very headache.
However, Little Gyro was invited to complete a math quiz someday, the information relating to this shown as the following:
What follows are some simple arithmetic problems. Therefore, it should be quite easy for you to get the correct answers. However, you are in a different country named Praha and the symbols for multiplication, addition, division, and subtraction follow a different logic, but fortunately all the arithmetic expressions in this country still follow the regular arithmetic rules. They are as follows:

It's considered that Little Gyro can't find the symbol '×' or '÷' on his laptop keyboard, so he always uses the symbol '*' to represent the symbol '×' as well as the symbol '/' to represent the symbol '÷'.
Due to calculating the arithmetic problems which seems to be a little bit difficult for Little Gyro, he wrote a simple program to solve those problems perfectly at last. Now Little Gyro sends this task to you.

输入描述

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')

上一题