第三届中国计量大学ACM程序设计竞赛个人赛(同步赛)A.Arithmetic Problems

第三届中国计量大学ACM程序设计竞赛个人赛(同步赛)A.Arithmetic Problems

题目链接

题目描述

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:
第三届中国计量大学ACM程序设计竞赛个人赛(同步赛)A.Arithmetic Problems_第1张图片
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 × 1 0 5 5×10^5 5×105characters) from the different country Praha, which only contains non-negative integers (no more than 1 0 5 10^5 105), 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 1 0 − 10 10^{-10} 1010 and 1 0 10 10^{10} 1010 .

示例1

输入

1 + 1 / 1 * 1 - 1

输出

1.00

示例2

输入

2/0+0-3*4

输出

Cannot be divided by 0

这题就是计算表达式,但是注意表达式的运算都换了,我看到了过的代码里用 python 写的,真的太妙了,用一个 eval 函数就可以了,太妙了,AC代码如下:

import sys
sys.setrecursionlimit(600000)
s=input()
s=s.replace(' ','')
s=s.replace('-','mul')
s=s.replace('/','add')
s=s.replace('+','div')
s=s.replace('*','sub')
s=s.replace('mul','*')
s=s.replace('add','+')
s=s.replace('div','/')
s=s.replace('sub','-')
try:
    print("{:.2f}".format(eval(s)))
except:
    print("Cannot be divided by 0")

你可能感兴趣的:(python)