农民领袖
- 积分
- 11702
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2010-12-24
- 最后登录
- 1970-1-1
|
本帖最后由 diamrem 于 2011-4-21 17:24 编辑
我不会C++,C也只是懂皮毛
于是拿python写了一个,可以处理小数的,空格应该也考虑了。
话说,这里的code模块是不是不支持Python
#!/usr/bin/python
# encoding:UTF-8
add_sub = ['-','+']
mul_div = ['*','/']
def parse(input, pattern):
'''
parse the input string to a raw list
every elemtns in the list is either an operand or operator
treat add/substruct and multiply/division differently
the operand of add/sub could be a expression of mult/div
'''
raw_list = []
digits = ''
index = 0
for c in input.strip():
index += 1
if c == ' ':
#check if space
continue
elif c not in pattern:
#if not a operator store it
digits += c
if index == len(input):
raw_list.append(digits)
elif c in pattern:
#if find a operator, append the formal found digits
#to the output list
raw_list.append(digits)
raw_list.append(c)
digits = ''
return raw_list
def cal_unit(expression):
oper1, sign, oper2 = expression
oper1 = check_if_mult_div(oper1)
oper2 = check_if_mult_div(oper2)
if sign == '+':
result = oper1+oper2
if sign == '-':
result = oper1-oper2
if sign == '/':
result = oper1*1.0/oper2
if sign == '*':
result = oper1*oper2
return str(result)
def check_if_mult_div(operand):
if operand.find('/') == -1 and operand.find('*') == -1:
return float(operand.strip())
else:
#if the operand contains * or /, calculate it
return float(cal_all(parse(operand, mul_div)))
def cal_all(list):
#user recursion to calculate the whole list
if len(list) == 3:
return cal_unit(list)
else:
return cal_all([cal_unit(list[:3])]+list[3:])
if __name__=='__main__':
a = raw_input('Enter:')
print cal_all(parse(a, add_sub)) |
|