Recursion 2: Solving the problem of recursive definition

2. To solve the problem of recursive definition:

In the problem of recursive definitions, we can clearly see the nesting nature of the definitions. Here are two examples to illustrate.

Question 1: Solve the inverse Polish expression

Title description: Inverse Polish expression is an arithmetic expression that precedes operators (in fact, this expression is called Polish expression in general textbooks). For example, the inverse Polish expression of ordinary expression 2 + 3 is + twenty three. The advantage of reverse Polish expressions is that there is no need to have a precedence relationship between operators, and there is no need to use parentheses to change the order of operations. For example, the reverse Polish notation of (2 + 3) * 4 is * + 2 3 4. This problem solves the value of the reverse Polish expression, where the operators include +-* / four. For details, please see: Inverse Polish Expression-Wikipedia

In fact, the definition of reverse Polish expression here can be regarded as: operator reverse Polish expression reverse Polish expression , a value can also be regarded as a reverse Polish expression. This will be the end condition of the recursive operation of the reverse Polish expression.

Although inverse Polish expressions are often solved based on stacks, we can see that the definition itself is a recursive form through the form of its definition. That is, the inverse Polish expression itself contains the inverse Polish expression.
Solving process:

1. Enter a string to represent the reverse Polish expression
2. According to the first character in the string, determine the addition, subtraction, multiplication, and division operation
3. Recursively call the input reverse Polish expression to perform operation
4, until the input reverse Polish does not add or subtract When multiplying and dividing characters, the boundary condition of the recursive call is reached, and the value is returned at this time.

The following is the result achieved using C++:

#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
double exp() {
    
    
	char s[20];
	cin >> s;
	
	switch(s[0]) {
    
    	//根据第一个运算符来判断什么运算
		case '+':
			return exp() + exp();
		case '-':
			return exp() - exp();
		case '*':
			return exp() * exp();
		case '/':
			return exp() / exp();
		default:	//边界条件,返回该值
			return atof(s);		//将字符串转化为数字,在<cstdlib>中 
	} 
}

int main() {
    
    
	printf("%lf",exp());
	return 0;
}

Operating results:
Insert picture description here
PS: In textbooks, operators are generally referred to as Polish expressions in front of them, while inverse Polish expressions are called suffixes. This is a bit different from this question, but the problem is not big (# . #).

Question 2: Expression evaluation calculation:

Problem description: The input is four arithmetic expressions, which are only composed of integers, +, -, *, /, (,) without spaces , and their values ​​are required to be evaluated. Assume that the operator results are all integers. "/" The result is also an integer

It can be found that the expression itself is a recursive definition, we can think of it like this:

The expression is composed of terms, the terms are composed of factors, and the factors are composed of expressions or integers.
Expression: item by subtraction to obtain calculation
term: factor by multiplication and division to give operational
factors: including numbers in the expression , or is an integer

The following is a picture to illustrate: It
Insert picture description here
can be found that the calculation expression itself contains calculation items, and the calculation items contain calculation factors, which in turn require calculation items . Therefore, it can be found that this is a recursive nested call process.

The following is the C++ code implementation:

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

int factor_value();		//求因子
int term_value();		//求项的值
int expression_value();	//求表达式的值

int main() {
    
    
	cout << expression_value() << endl;
	return 0;
}
/*--- 求一个表达式的值 ---*/
int expression_value() {
    
     
	int result = term_value();		//求第一项的值 

	while (true) {
    
    
		char op = cin.peek();		//从输入流中读取第一个字符,用来判断其符号类型 ,只是**查看,不是取出**
		if (op == '+' || op == '-')  {
    
     //如果该字符是+或-的话需要进行下一项的读取操作,并将该符号从输入流中拿走
			cin.get();				
			int value = term_value();	//读取下一项
			//对结果进行加减运算
			if (op == '+') 
				result += value;
			else 
				result -= value; 
		} else 
			break;	
	}
	return result;
}
/*--- 计算项的值 ---*/
int term_value() {
    
    
	int result = factor_value();	//求第一因子的值
	
	while (true) {
    
    
	 	char op = cin.peek();
	 	if (op == '*' || op == '/') {
    
    
	 		cin.get();
	 		int value = factor_value();
	 		if (op == '*') 
	 			result *= value;
	 		else 
	 			result /= value;
		 } else 
		 	break;
	}
	
	return result;
}
/*--- 计算因子的值 ---*/
int factor_value() {
    
    
	int result = 0;
	char c = cin.peek();
	if (c == '(') {
    
    	//如果是括号则需要进行项的运算
		cin.get();
		result = expression_value();
		cin.get();	//将输入流中的‘)’取走
	} else {
    
    
		while (isdigit(c)) {
    
    	//最后的因子是数字字符的情况
			result = 10 * result + c - '0';
			cin.get();
			c = cin.peek();
		}
	}
	
	return result;
}

Operation result: the correct result can be output.
Insert picture description here
Other contents of recursion can be viewed:
Recursion One: Replace multiple loops
Recursion Three: Break down the problem into smaller scales

Guess you like

Origin blog.csdn.net/weixin_44184990/article/details/105174644