Python implements a simple arithmetic calculator _python

Source: Internet
Author: User
Tags arithmetic

First, the algorithm

1, the main idea of the algorithm is to convert an infix expression (Infix expression) into a convenient suffix expression (Postfix expression), and then with the help of the stack of this simple data structure, to calculate the results of the expression.

2, on how to speak the ordinary expression to the suffix expression, and how to deal with the suffix expression and calculate the results of the specific algorithm description is not described here, the book has a detailed description.

Second, simple calculator

Instructions for use

A simple example of using this calculator class is as follows:

# usage
c = Calculator ()
print (' result: {: F} '. Formart (C.get_result (' 1.11+2.22-3.33*4.44/5.55 '))
# Output:
result:0.666000

Test Cases

In order to effectively test the calculator, several sets of test cases were designed, and the test results were as follows:

Test No.1: (1.11) = 1.110000
Test no.2:1.11+2.22-3.33*4.44/5.55 = 0.666000
Test no.3:1.11+ (2.22-3.33) *4.44/ 5.55 = 0.222000
Test no.4:1.11+ (2.22-3.33) * (4.44+5.55)/6.66 = -0.555000
Test no.5:1.11* ((2.22-3.33) * (4.44+ 5.55)/(6.66+7.77) = -0.852992
Test no.6: (1.11+2.22) * (3.33+4.44)/5.55*6.66 = 31.048920
Test no.7: (1.11-2.22) /(3.33+4.44)/5.55* (6.66+7.77)/(8.88) = -0.041828
Test no.8:error: (1.11+2.22) * (3.33+4.44:missing ")", please Check your expression
Test no.9:error: (1.11+2.22) *3.33/0+ (34-45): divisor cannot be zero
test no.10:error:12+8 9^7:invalid Character: ^

Implementation code

The implementation of the stack

The stack is actually a restricted operation table, all operations can only at the top of the stack (into the stack, out of the stack, etc.), the following is the use of Python code to achieve a simple stack:

 class Stack (object): "" "The Structure of a stack.
  The user don ' t have to know the definition. "" "Def __init__ (self): Self.__container = List () def __is_empty (self):" "" Test if the stack is empty or Not:return:True or False "" "Return len (self.__container) = = 0 def push (self, Element):" "" Add A new element to the stack:p Aram element:the element, want to Add:return:None "" Self.__container.ap Pend (Element) def top (self): "" "" "" The Stack:return:top Element "" If self._ _is_empty (): Return to None return self.__container[-1] def pop (self): "" "" Stack:return:None or the top element of the stack ' "" Return None if Self.__is_empty () Else Self.__container
    . Pop () def Clear (self): "" We'll make an empty Stack:return:self "" "Self.__container.clear () return self 

Implementation of Calculator class

In the Calculator class, we complete the validation of the expression in a single function, but in fact, if necessary, it can be implemented directly in the function of the infix expression suffix expression, so that only one traversal of the expression is required to complete the validation and conversion work. But in order to keep the structure clear, or separate to achieve better, each function as best as possible one thing is more real.

In this calculator class, there are many kinds of extreme situations that are not considered, because then the entire implementation of the code will be more. However, it is possible to extend the entire class later on, adding new features. At present, the main framework, including basic error detection and operation, focus on learning to use the stack this seemingly simple but powerful data structure to solve the problem.

Class Calculator (object): "" "A simple Calculator, just for Fun" "Def __init__ (self): Self.__exp = ' Def
    __validate (self): "" We have to make sure the expression is legal. 1. We only accept the ' () ' to specify the priority of a sub-expression.
    Notes: ' [{' and ']} ' would be replaced by ' (' and ') ' respectively. 2. Valid characters should be ' + ', '-', ' * ', '/', ' (', ') ' and numbers (int, float)-Invalid expression examples, but We can only handle the 4th case.
      The implementation is much more sophisticated if we want to handle all possible cases.: 1. ' A+b-+c ' 2. ' a+b+-' 3.
      ' A + (B+c ' 4. ' + (+b-) ' 5 etc:return:True or False ' "' If not isinstance (Self.__exp, str): Print (' Error: {}: Expression should is a string '. Format (SELF.__EXP)) return False # Save the Non-space Expressio n Val_exp = ' s = Stack () for x in Self.__exp: # We should ignore the spaces characters if x = = ': Continue if Self.__is_bracket (x) or Self.__is_digit (x) or self.__is_operators (x) \
      or x = = '. ': if x = = ' (': S.push (x) elif x = = ') ': S.pop () Val_exp + = X
      Else:print (' Error: {}: Invalid character: {} '. Format (self.__exp, x)) return False if S.top (): Print (' Error: {}: Missing '), please check your expression '. Format (SELF.__EXP)) return False Self.__exp = Val_exp return True def __convert2postfix_exp (self): "" "Convert the infix expression to a postfix Expressio N:return:the converted expression "" "# Highest Priority: () # middle: */# Lowest: +-Convert 
      Ed_exp = ' Stk = Stack () for x in Self.__exp:if self.__is_digit (x) or x = = '. ': Converted_exp + = x Elif self.__is_operators (x): Converted_exp + = ' TP = stk.top () if tp:if tp = = ' (': Stk.pusH (x) Continue x_pri = self.__get_priority (x) Tp_pri = self.__get_priority (TP) if
            X_pri > Tp_pri:stk.push (x) elif X_pri = = tp_pri:converted_exp + + = Stk.pop () + ' " Stk.push (x) else:while stk.top (): If Self.__get_priority (Stk.top ())!= x_p
        Ri:converted_exp + + stk.pop () + ' Else:break stk.push (x)
          Else:stk.push (x) elif Self.__is_bracket (x): Converted_exp + = ' if x = = ' (': 
          Stk.push (x) else:while stk.top () and Stk.top ()!= ' (': Converted_exp + = Stk.pop () + ' Stk.pop () # Pop all the operators while Stk.top (): Converted_exp + = ' + stk.pop () + ' RET  Urn Converted_exp def __get_result (self, operand_2, operand_1, operator): if operator = ' + ': return operand_1 + operand_2 elif opErator = ': return operand_1-operand_2 elif operator = = ' * ': return operand_1 * operand_2 elif op  Erator = = '/': if Operand_2!= 0:return operand_1/operand_2 else:print (' Error: {}: Divisor Cannot is zero '. Format (SELF.__EXP) return to None def __calc_postfix_exp (self, exp): "" "Get the result F Rom a converted Postfix expression e.g. 6 5 2 3 + 8 * + 3 + *: Return:result "" "Assert Isinstance (exp, s
        TR) Stk = Stack () Exp_split = Exp.strip (). Split () for x in Exp_split:if self.__is_operators (x):
          # pop two top numbers on stack r = Self.__get_result (Stk.pop (), Stk.pop (), X) if R is None: Return None Else:stk.push (R) Else: # Push the converted number to the stack Stk. Push (float (x)) return Stk.pop () def __calc (self): "" ' Try to get ' The result of the Expression:return:n
  One or result ""  # Validate if Self.__validate (): # Convert, then run the algorithm to get the result return self.__calc_ Postfix_exp (Self.__convert2postfix_exp ()) Else:return None def get_result (self, expression): "" "Get The result is a expression suppose we have got a valid Expression:return:None or result "" Self.__exp = Expression.strip () return Self.__calc () "" "Utilities" "" @staticmethod def __is_operators (x): Return x in [' + ', '-', ' * ', '/'] @staticmethod def __is_bracket (x): return x in [' (', ') '] @staticmethod def __is_dig It (x): Return X.isdigit () @staticmethod def __get_priority (OP): If op in [' + ', '-']: return 0 elif O p in [' * ', '/']: return 1

Summarize

The above is the use of Python to achieve a simple arithmetic calculator all the content, I hope the content of this article for everyone's study or work can help, if there is doubt you can message exchange.

Reference

Description of the relevant chapters in the data structure and algorithm (C language)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.