Python Regular Expression job calculator, python Regular Expression

Source: Internet
Author: User

Python Regular Expression job calculator, python Regular Expression

Job: calculator Development

Implements addition, subtraction, multiplication, division, and extension priority resolution
User input 1-2*(60-30 + (-40/5) * (9-2*5/3 + 7/3*99/4*2998 + 10*568/14 )) -(-4*3)/(16-3*2) after a similar formula, you must resolve the (), +,-, *,/, and formula in it, the result obtained after calculation must be consistent with the result obtained by the real calculator.
I. Description:

One bug is that the power cannot be calculated. For example, if '6 ** 6', an error is reported.

Idea Of This calculator:
1. recursion is useless. First, find and calculate the formulas in All parentheses, and then calculate multiplication, division, and addition and subtraction.
2. All numbers are regarded as floating-point operations to retain decimal places.
Technology used:
1. Regular Expression
2. tkinter

Ii. flowchart:

 

3. The Code is as follows:

#! /Usr/bin/env python3 # antuor: Alan import refrom functools import performancefrom tkinter import * ''' handles special-number operations ''' def minus_operation (expresstion): minus_operators = re. split ("-", expresstion) calc_list = re. findall ("[0-9]", expresstion) if minus_operators [0] = "": calc_list [0] = '-% s' % calc_list [0] res = reduce (lambda x, y: float (x)-float (y), calc_list) print (">>>>>>>>>>>>>> minus [% s] Calculation Result:" % expresstion, res) return res ''' reduce () function is used continuously for sequence. If initial is not given, two elements of sequence are called for the first time, later, the result of the previous call and the next element of sequence will be passed to the function ''''' to process the dual operator number ''' def del_duplicates (expresstion): expresstion = expresstion. replace ("++", "+") expresstion = expresstion. replace ("--", "-") expresstion = expresstion. replace ("+-", "-") expresstion = expresstion. replace ("--", "+") expresstion = expresstion. replace ('--', "+") e return expresstion ''' */operation function ''' def mutiply_dividend (expresstion): calc_list = re. split ("[*/]", expresstion) # Use * or/to separate the formula operators = re. findall ("[*/]", expresstion) # Find all * And/number res = None for index, I in enumerate (calc_list): if res: if operators [index-1] = '*': res * = float (I) elif operators [index-1] = '/': res/= float (I) else: res = float (I) procession0 = "[% s] operation result =" % expresstion, res final_result.insert (END, procession0) # Insert Form print (procession0) return res ''' Processing Operator number order disorder ''' def special_features (Measures, multiply_and_dividend): for index, I in enumerate (multiply_and_dividend): I = I. strip () if I. endswith ("*") or I. endswith ("/"): partition [index] = multiply_and_dividend [index] + partition [index] + multiply_and_dividend [index + 1] del multiply_and_dividend [index + 1] del partition [index] return partition, multiply_and_dividend def minus_special (operator_list, calc_list): for index, I in enumerate (calc_list): if I = '': calc_list [index + 1] = I + calc_list [index + 1]. strip () ''' operation except () formula +-*/''' def figure_up (expresstion): expresstion = expresstion. strip ("()") # remove the outer brackets expresstion = del_duplicates (expresstion) # Remove the duplicate +-number plus_and_minus_operators = re. findall ("[+-]", expresstion) multiply_and_dividend = re. split ("[+-]", expresstion) if len (multiply_and_dividend [0]. strip () = 0: multiply_and_dividend [1] = primary [0] + primary [1] del primary [0] del primary [0] Primary, multiply_and_dividend = special_features (primary, multiply_and_dividend) for index, I in enumerate (multiply_and_dividend): if re. search ("[*/]", I): sub_res = mutiply_dividend (I) Returns [index] = sub_res print (multiply_and_dividend, records) # Calculate final_res = None for index, item in enumerate (multiply_and_dividend): if final_res: if plus_and_minus_operators [index-1] = '+': final_res + = float (item) elif plus_and_minus_operators [index-1] = '-': final_res-= float (item) else: final_res = float (item) procession = '[% s] calculation result: '% expresstion, final_res final_result.insert (END, procession) # Insert Form print (procession) return final_res "main function: operation logic: first calculate the value in the extension number, calculate and multiply, and then add or subtract "def calculate (): expresstion = expresstions. get () # get the value of the input box flage = True calculate_res = None # initialize the calculation result to None while flage: m = re. search ("\ ([^ ()] * \)", expresstion) # first find the bottom layer () # pattern = re. compile (r "\ ([^ ()] * \)") # m = pattern. match (expresstion) if m: sub_res = figure_up (m. group () # formula expresstion = expresstion in the operation. replace (m. group (), str (sub_res) # Replace the formula else: print ('--------------- the brackets have been calculated --------------') procession1 = "Final calculation result :", figure_up (expresstion) final_result.insert (END, procession1) # Insert Form print ('\ 033 [31m final calculation result:', figure_up (expresstion )) flage = False if _ name __= = "_ main _": # res = calculate ("1-2*(60-30 + (-40/5) * (9-2*5/3 + 7/3*99/4*2998 + 10*568/14)-(-4*3)/(16-3*2 ))") window = Tk () ### create a window. title ('calculator') ### name form frame1 = Frame (window) ### framework 1 frame1.pack () ### place frame2 = Frame (window) ### framework 2 frame2.pack () ### place lable = Label (frame1, text = "Enter the formula:") ### text Label lable. pack () expresstions = StringVar () ### input box attributes, string entryname = Entry (frame1, textvariable = expresstions) ### text input box bt_get_expresstions = Button (frame1, text = "Submit", command = calculate) ### button pendant bt_get_expresstions.pack () entryname. pack () lable. grid (row = 1, column = 1) ### position entryname. grid (row = 1, column = 2) bt_get_expresstions.grid (row = 1, column = 3) final_result = Text (frame2) ### final_result.tag_config ("here ", background = "yellow", foreground = "blue") final_result.pack () window. mainloop () ### event Loop

The above is all the content of this article, hoping to help you learn.

Articles you may be interested in:
  • Python simple calculator program, just a few lines of code
  • Examples of Regular Expression usage in Python
  • Python Regular Expression matches IP address instances
  • Usage of Regular Expressions in python
  • Regular Expressions in Python
  • Basic expression for writing python Crawlers
  • Example of python regular expression match and search usage
  • Python regular expressions match HTML page Encoding
  • Use only 50 lines of code to implement a Python calculator tutorial
  • Python uses regular expressions to extract webpage URLs

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.