Using Python to operate a string expression

Source: Internet
Author: User

Overview:How to run an expression, for example: 12+23*4/2 This I think we all know very well. But what if the expression is a string? Or so to describe, an expression is written as a string, and how do we run it and get the value? Would you think if we could get 12, 23, 4, 2 and the middle operator, that would be really great. And in fact, we are working in this direction. If you have studied algorithms or data structures, then I think this little problem will not stop you from moving forward.

Thinking Analysis:as the overview says, if we can get the "elements" in the string expression that we can identify with our eyes, even if we take the first step. What the! Just the first step? Yes, that's the first step. What's the second step?
Yes, the second step is arithmetic. The process of the operation will have a problem, this problem is the operator priority problem, take the above expression, we need to do 23*4 operation, rather than 12+23 operation. All we have to do is let the computer do the math according to the priority of our cognition. The stupid way to do this is to go through the two-pass expression in turn (in fact, in later operations, we're traversing a list). First time do multiplication, the second time and then do add and subtract.

element Separation:It's really easy to do this in Python, because our cute python can store different types of objects in the list . This is a bit like the struct in C and the class in Java. The first thing we get is a character, and then we iterate over and sort the characters (numbers or operators).

# split Expressiondef mixed_operation (exp):    exp_list = List (exp)    temp = '    behavor_list = []    i = 0    le Ngth = Len (exp_list) for    item in Exp_list:        if Is_operation (item):            behavor_list.append (int (temp))            Behavor_list.append (item)            temp = '        else:            temp + = Item        If i = = length-1:            behavor_list.append (int (temp))            break;        i + = 1    return behavor_list

Logical Operation:This function is somewhat special, and may not be familiar to a friend with programming experience. Yes, it's recursion ! For a coder, recursion is a must, so let's get the recursion together at the right time. The reason to write recursion here is that every operator in our expression cannot have just one. We're going to go through this all the time. At this point you may already feel, traverse the words, why not use for? Yes, there is a for loop code in my code, but the for is not as good as it is imagined, and you can try it if you don't believe it.

# calculation OP1 and OP2 (' * ' and '/' or ' + ' and '-') def cal_op1_op2 (Exp_list, OP1, OP2):    If Len (exp_list) = = 1:        r Eturn exp_list            i = 0    has_op = False for    i in range (2, Len (exp_list), 2):        a = exp_list[i-2]        o = exp_l IST[I-1]        b = exp_list[i]        if o = = OP1 or o = = op2:            has_op = True            exp_list[i-2] = Get_aob (A, O, b) 
   
    del Exp_list[i]            del exp_list[i-1]            break    if has_op = = False:        return exp_list    return cal_op1_ OP2 (Exp_list, OP1, OP2)
   

Special Note:Of course, this program is not so robust. Because our logic is that we get a normal expression, and we don't include parentheses. The so-called normal expression is that there will not be a few characters or fewer operators or input non-' + ', '-', ' * ', '/', [0-9] character or character set. Our program defaults to an ideal operating environment, because it is just the idea of the code.

complete code is included:

#!/usr/bin/env python ' expression_cal.py-cal the expression that's give to me ' # judgment a char is a operation or NOTD        EF is_operation (oper): if oper = = ' + ' or oper = = '-' or oper = = ' * ' or oper = = '/': return True else: Return false# split expressiondef mixed_operation (exp): exp_list = LIST (exp) temp = ' Behavor_list = [] i = 0 length = Len (exp_list) for item in Exp_list:if is_operation (item): behavor_list.append (int (temp )) Behavor_list.append (item) temp = ' Else:temp + = Item if i = = Length-        1:behavor_list.append (int (temp)) break;        i + = 1 return behavor_list# cal a O bdef get_aob (A, O, b): if o = = ' + ': return a + b elif o = = '-':  return a elif o = = ' * ': return a * b elif o = = '/': return a/b# calculation op1 and OP2 (' * ' and '/' or ' + ' and '-') def cal_op1_op2 (Exp_list, OP1, OP2): If Len (exp_list) = = 1:return Exp_list i = 0 Has_op = False for I in range (2, Len (exp_list), 2): a = Exp_li            St[i-2] o = exp_list[i-1] b = exp_list[i] if o = = OP1 or o = = Op2:has_op = True Exp_list[i-2] = Get_aob (A, O, b) del Exp_list[i] del exp_list[i-1] break if Has_op = = False:return exp_list return cal_op1_op2 (Exp_list, OP1, OP2) # cal Expdef Cal_exp (exp_list): Exp_li    st = CAL_OP1_OP2 (exp_list, ' * ', '/') Exp_list = Cal_op1_op2 (exp_list, ' + ', '-') return exp_list[0]while True: Expre = Raw_input (' Enter your expression (0 to end): \ n ') if Expre = = ' 0 ': Break result = mixed_operation (expr e) print ' list result = ', print result print cal_exp (result) print ' END '


Using Python to operate a string expression

Related Article

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.