简单的计算程序
Friday, 22 April 2011
今天的题目是:
如何写出一个简单的4则运算的程序。如输入 ” 1 -2*3 + 6/3″ ,输出 -3。只用支持正整数,不用考虑有括号的情况。
思路:因为不用考虑括号,所以乘和除的优先级最高。可以先把输入字符串用“+”和“-”分隔成一个数组,数组的结构是一个数字和符号间隔,把乘除法的项当作一个数字处理,如题目中的输入会被分成[“1″,”-“,”2*3″,”+”,”6/3″],然后再每三个数组项计算一次,把得到的结果加入到剩下的数组里,递归计算。如果计算过程中碰到还有乘除法的项,如”2*3″,则先把这个项算出来。
具体代码如下:
#!/usr/bin/python # encoding:UTF-8 ''' Calculate the input string and output the result. For input of '1-2*3+6/3', output -3 Only consider the situation of int, assume no "(" in the string ''' 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))