The 1th question of the first chapter of modern software Engineering--Deng Kun

Source: Internet
Author: User

Title Requirements:

Step one: like Chiu, spend 20 minutes writing a command-line "software" that automatically generates arithmetic topics for primary schools , respectively, to meet the requirements below. The following requirements can be specified in the form of command-line arguments:

a) in addition to integers, support the arithmetic of true fractions. (Example: 1/6 + 1/8 = 7/24)

b) allow the program to accept the user to enter the answer and determine the right and wrong. Finally, the total number of pairs/errors is given.

c) gradually expand the functionality and the types of expressions that can be supported, and finally you want to support the following types of topics (up to 10 operators, the number of parentheses is unlimited):
25-3 * 4-2/2 + 89 =?
1/2 + 1/3-1/4 =?
(5-4) * (3 +28) =?

d) can be in bulk out of more than 100 questions, saved in a text file, and ensure that the title can not be repeated, (1+2) and (2+1) is a recurring topic. How to ensure that the problem is not repeated, please see the detailed topic requirements

And the students compare the function of the respective programs, performance, the similarities and differences of implementation methods and so on.

How do I evaluate an expression? Resources:

Http://hczhcz.github.io/2014/02/27/shunting-yard-algorithm.html

Https://en.wikipedia.org/wiki/Shunting-yard_algorithm

In view of the difficulty and workload of the problem, I split the problem into 3 small phases to implement:

1: Evaluation of composite arithmetic

2: Randomly generated composite arithmetic

3: Increase support for true and false scores

Analysis: 1. For the evaluation of composite arithmetic, according to the characteristics of the stack, using the priority comparison of arithmetic compliance, the complex arithmetic evaluation, the detailed algorithm process will be described below.

2. Random generation of composite arithmetic is a difficult problem in this topic, after thinking about it, I think we can use multiple random processes to generate arithmetic expressions. For the first time, randomly participate in the calculation of the number of numbers, the second, the number of random numbers, the third, the arithmetic between random numbers, the fourth time, the addition of random parentheses. Note that because there may be a 0 operation , this error condition should be excluded from the line. Due to the particularity of the three and fourth random processes, even in the third step, for example: 3/0 + 1, the arithmetic expression, but if the fourth random process generates parentheses outside of the calculation 0 + 1, resulting in 3/(0 + 1) result, this calculation is also correct. Therefore, it is not guaranteed to make a judgment of 0 in the process of randomly generating compound arithmetic.

For this problem, my personal thinking is: after the generation of each composite arithmetic, the evaluation of the composite operation, and in the algorithm every time the evaluation process to judge, if there are 0 errors, throw an exception, mark the current generated arithmetic is illegal, to regenerate. Although there are a lot of cases except 0, it wastes a lot of time to judge, but the time complexity and space complexity of the problem are very small and negligible.

3. When adding true and false fractional operations, only one condition is required for each arithmetic, so there is no greater difficulty.

Evaluation of compound arithmetic

An algorithm for evaluating an expression:

I am using the operator precedence method, in which the order of precedence is:

1, the highest precedence of parentheses, the various operators in parentheses are: first multiplication, then add and subtract, the same sibling operation from the right

2, in parentheses, outside the brackets, the multi-layer brackets, from inside out.

Operands can be constants, variables, constants.
Operators have arithmetic operators, relational operators, and logical operators.
The bounds character includes the left and right parenthesis calculation terminator.
Operators and bounds Fu Shi are called "operators."

  

In the operator set, in each operation step, the relationship between the adjacent operator C1 and C2 is the following three cases (C1 appears before C2):
C1<C2,C1 priority is lower than C2
The priority of C1=C2,C1 equals C2
C1>C2,C1 priority is greater than C2

Precedence of the operator described:

To implement the operator precedence algorithm, two working stacks are used here. One holds the operator optr, and the other holds the data opnd. The algorithm idea is:


(1) First, the data stack is empty, and the expression start character "#" is the stack-bottom element that calculates Fu Yi.
(2) From left to right scan expression, read the operand into the OPND stack, read the operator, and the optr stack top element comparison (stack top element is C1, read the operator is C2);
If C1<C2, then the C2 stack continues to scan the back expression;
If C1=C2, then ("="), that is, in parentheses, the end of the operation, will be C1 out of the stack, and C2 abort, and after the operation of the stack scan the following expression;
If C1>C2, then will c1 out of the stack, and in the operand stack out two elements a and B by C1 do the operation, the results of the operation into the OPND.
Repeat until the expression evaluates to a complete value.

For example: expression (7-2), the evaluation process is as follows:

Steps Optr Stack OPND Stack Input character Main operation
1 # (7-2) # PUSH (OPND, ' 3 ')
2 # 3 * (7-2) # PUSH (optr, ' * ')
3 #* 3 (7-2) # PUSH (Optr, ' (')
4 #*( 3 7-2) # PUSH (OPND, ' 7 ')
5 #*( 3 7 -2) # PUSH (optr, '-')
6 #*(- 3 7 2) # PUSH (OPND, ' 2 ')
7 #*( 3 7 2 )# Operate (7-2)
8 #*( 3 5 )# Pop ()
9 #* 15 # Operate (3*5)
10 # 15 # PUSH (Optr, ' # ')

To make the two operators more convenient, give the operator priority, such as the following table, where C1 is the element inside the stack, C2 is the outside element:

Operator comparison algorithm:  

CharPrecede (CharC1,CharC2) {intC_TEMP1,C_TEMP2;Switch(C1) { Case‘*': Case'/': c_temp1=4; Break; Case' +': Case'-': c_temp1=2; Break; Case' (': c_temp1=0; Break; Case') ': c_temp1=5; Break; Case' # ': c_temp1=-1;}

Switch(C2) { Case‘*': Case'/': c_temp2=3; Break; Case' +': Case'-': c_temp2=1; Break; Case' (': c_temp2=5; Break; Case') ': c_temp2=0; Break; Case' # ': c_temp2=-1;}if(C_TEMP1&LT;C_TEMP2)return(' <');if(C_TEMP1=C_TEMP2)return(' =');if(C_TEMP1&GT;C_TEMP2)return(' >');}

intExpress () {initstack (optr); Push (Optr, ' # '); Initstack (OPND); W=GetChar (); while(w!= ' # ' | | GetTop (optr)! =' # ') {if(! In (W,op)) {Push (opnd,w); w=GetChar ();}Else        //OP is a collection of operatorsSwitch(Precede (GetTop (optr), W)) { Case' < ': Push (optr,w); W=getchar (); Break; Case' = ': Pop (optr); W=getchar (); Break; Case' > ': Op=pop (optr); B=pop (OPND); a=Pop (OPND);p Ush (Opnd,operate (a,op,b)); Break;}}return(Getop (OPND));

Operator-first algorithm to evaluate the expression value:

Operandtype evaluateexpression () {initstack (optr);    Push (Optr, ' # '); Initstack (OPND); C=GetChar ();  while(c!= ' # ' | | GetTop (optr)! =' # ') {        if(!In (C,OP))            {Push (opnd,c); C=GetChar ();} Else            Switch(Precede (GetTop (optr), c) { Case' < '://stack top element priority lowPush (OPTR,C); C=GetChar ();  Break;  Case' = '://ParenthesisPop (OPTR,X); C=GetChar ();  Break;  Case' > '://stack up and calculatePop (Optr,theta); Pop (OPND,B);                Pop (Opnd,a);                Push (OPND, Operate (a,theta,b));  Break; }//Switch}// while    returnGetTop (OPND);}//evaluateexpression            

Modern software Engineering the first chapter of introduction to the 1th question--Deng Kun

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.