前缀、中缀、后缀表达式

前缀中缀后缀表达式介绍 一前缀表达式 1 前缀表达式又称波兰式,前缀表达式的运算符位于操作数之前。 2 举例 (3+4)×5-6 对应的前缀表达式是: - × + 3 4 5 6 3前缀表达式的计算机求值过程 从右至左扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(栈顶元素 和 次顶元素),并将结果入栈;重复上述过程直到表达式最左端,最后运算得出的值即为表达式的结果。 例如: (3+4)×5-6 对应的前缀表达式就是 - × + 3 4 5 6 , 针对前缀表达... 阅读详情
       它们都是对表达式的记法,因此也被称为前缀记法、中缀记法和后缀记法。它们之间的区别在于运算符相对与操作数的位置不同:前缀表达式的运算符位于与其相关的操作数之前;中缀和后缀同理。

举例:
(3 + 4) × 5 - 6 就是中缀表达式
- × + 3 4 5 6 前缀表达式
3 4 + 5 × 6 - 后缀表达式

中缀表达式(中缀记法)
中缀表达式是一种通用的算术或逻辑公式表示方法,操作符以中缀形式处于操作数的中间。中缀表达式是人们常用的算术表示方法。
虽然人的大脑很容易理解与分析中缀表达式,但对计算机来说中缀表达式却是很复杂的,因此计算表达式的值时,通常需要先将中缀表达式转换为前缀或后缀表达式,然后再进行求值。对计算机来说,计算前缀或后缀表达式的值非常简单。

前缀表达式(前缀记法、波兰式)
前缀表达式的运算符位于操作数之前。

前缀表达式的计算机求值:
从右至左扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(栈顶元素 op 次顶元素),并将结果入栈;重复上述过程直到表达式最左端,最后运算得出的值即为表达式的结果。
例如前缀表达式“- × + 3 4 5 6”:
(1) 从右至左扫描,将6、5、4、3压入堆栈;
(2) 遇到+运算符,因此弹出3和4(3为栈顶元素,4为次顶元素,注意与后缀表达式做比较),计算出3+4的值,得7,再将7入栈;
(3) 接下来是×运算符,因此弹出7和5,计算出7×5=35,将35入栈;
(4) 最后是-运算符,计算出35-6的值,即29,由此得出最终结果。
可以看出,用计算机计算前缀表达式的值是很容易的。

将中缀表达式转换为前缀表达式:
遵循以下步骤:
(1) 初始化两个栈:运算符栈S1和储存中间结果的栈S2;
(2) 从右至左扫描中缀表达式;
(3) 遇到操作数时,将其压入S2;
(4) 遇到运算符时,比较其与S1栈顶运算符的优先级:
(4-1) 如果S1为空,或栈顶运算符为右括号“)”,则直接将此运算符入栈;
(4-2) 否则,若优先级比栈顶运算符的较高或相等,也将运算符压入S1;
(4-3) 否则,将S1栈顶的运算符弹出并压入到S2中,再次转到(4-1)与S1中新的栈顶运算符相比较;
(5) 遇到括号时:
(5-1) 如果是右括号“)”,则直接压入S1;
(5-2) 如果是左括号“(”,则依次弹出S1栈顶的运算符,并压入S2,直到遇到右括号为止,此时将这一对括号丢弃;
(6) 重复步骤(2)至(5),直到表达式的最左边;
(7) 将S1中剩余的运算符依次弹出并压入S2;
(8) 依次弹出S2中的元素并输出,结果即为中缀表达式对应的前缀表达式。
例如,将中缀表达式“1+((2+3)×4)-5”转换为前缀表达式的过程如下:
扫描到的元素S2(栈底->栈顶)S1 (栈底->栈顶)说明
55空数字,直接入栈
-5-S1为空,运算符直接入栈
)5- )右括号直接入栈
45 4- )数字直接入栈
×5 4- ) ×S1栈顶是右括号,直接入栈
)5 4- ) × )右括号直接入栈
35 4 3- ) × )数字
+5 4 3- ) × ) +S1栈顶是右括号,直接入栈
25 4 3 2- ) × ) +数字
(5 4 3 2 +- ) ×左括号,弹出运算符直至遇到右括号
(5 4 3 2 + ×-同上
+5 4 3 2 + ×- +优先级与-相同,入栈
15 4 3 2 + × 1- +数字
到达最左端5 4 3 2 + × 1 + -空S1中剩余的运算符
因此结果为“- + 1 × + 2 3 4 5”。

后缀表达式(后缀记法、逆波兰式)
后缀表达式与前缀表达式类似,只是运算符位于操作数之后。

后缀表达式的计算机求值:
与前缀表达式类似,只是顺序是从左至右:
从左至右扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(次顶元素 op 栈顶元素),并将结果入栈;重复上述过程直到表达式最右端,最后运算得出的值即为表达式的结果。
例如后缀表达式“3 4 + 5 × 6 -”:
(1) 从左至右扫描,将3和4压入堆栈;
(2) 遇到+运算符,因此弹出4和3(4为栈顶元素,3为次顶元素,注意与前缀表达式做比较),计算出3+4的值,得7,再将7入栈;
(3) 将5入栈;
(4) 接下来是×运算符,因此弹出5和7,计算出7×5=35,将35入栈;
(5) 将6入栈;
(6) 最后是-运算符,计算出35-6的值,即29,由此得出最终结果。

将中缀表达式转换为后缀表达式:
与转换为前缀表达式相似,遵循以下步骤:
(1) 初始化两个栈:运算符栈S1和储存中间结果的栈S2;
(2) 从左至右扫描中缀表达式;
(3) 遇到操作数时,将其压入S2;
(4) 遇到运算符时,比较其与S1栈顶运算符的优先级:
(4-1) 如果S1为空,或栈顶运算符为左括号“(”,则直接将此运算符入栈;
(4-2) 否则,若优先级比栈顶运算符的高,也将运算符压入S1(注意转换为前缀表达式时是优先级较高或相同,而这里则不包括相同的情况);
(4-3) 否则,将S1栈顶的运算符弹出并压入到S2中,再次转到(4-1)与S1中新的栈顶运算符相比较;
(5) 遇到括号时:
(5-1) 如果是左括号“(”,则直接压入S1;
(5-2) 如果是右括号“)”,则依次弹出S1栈顶的运算符,并压入S2,直到遇到左括号为止,此时将这一对括号丢弃;
(6) 重复步骤(2)至(5),直到表达式的最右边;
(7) 将S1中剩余的运算符依次弹出并压入S2;
(8) 依次弹出S2中的元素并输出,结果的逆序即为中缀表达式对应的后缀表达式(转换为前缀表达式时不用逆序)。

例如,将中缀表达式“1+((2+3)×4)-5”转换为后缀表达式的过程如下:
扫描到的元素S2(栈底->栈顶)S1 (栈底->栈顶)说明
11空数字,直接入栈
+1+S1为空,运算符直接入栈
(1+ (左括号,直接入栈
(1+ ( (同上
21 2+ ( (数字
+1 2+ ( ( +S1栈顶为左括号,运算符直接入栈
31 2 3+ ( ( +数字
)1 2 3 ++ (右括号,弹出运算符直至遇到左括号
×1 2 3 ++ ( ×S1栈顶为左括号,运算符直接入栈
41 2 3 + 4+ ( ×数字
)1 2 3 + 4 ×+右括号,弹出运算符直至遇到左括号
-1 2 3 + 4 × +--与+优先级相同,因此弹出+,再压入-
51 2 3 + 4 × + 5-数字
到达最右端1 2 3 + 4 × + 5 -空S1中剩余的运算符

因此结果为“1 2 3 + 4 × + 5 -”(注意需要逆序输出)。

编写Java程序将一个中缀表达式转换为前缀表达式和后缀表达式,并计算表达式的值。其中的toPolishNotation()方法将中缀表达式转换为前缀表达式(波兰式)、toReversePolishNotation()方法则用于将中缀表达式转换为后缀表达式(逆波兰式):

注:
(1) 程序很长且注释比较少,但如果将上面的理论内容弄懂之后再将程序编译并运行起来,还是比较容易理解的。有耐心的话可以研究一下。(2) 此程序是笔者为了说明上述概念而编写,仅做了简单的测试,不保证其中没有Bug,因此不要将其用于除研究之外的其他场合。


[java]  view plain copy
  1. package qmk.simple_test;  
  2. import java.util.Scanner;  
  3. import java.util.Stack;  
  4. /** 
  5.  * Example of converting an infix-expression to 
  6.  * Polish Notation (PN) or Reverse Polish Notation (RPN). 
  7.  * Written in 2011-8-25 
  8.  * @author QiaoMingkui 
  9.  */  
  10. public class Calculator {  
  11.       public static final String USAGE = "== usage ==\n"  
  12.             + "input the expressions, and then the program "  
  13.             + "will calculate them and show the result.\n"  
  14.             + "input 'bye' to exit.\n";  
  15.       /** 
  16.        * @param args 
  17.        */  
  18.       public static void main(String[] args) {  
  19.             System.out.println(USAGE);  
  20.             Scanner scanner = new Scanner(System.in);  
  21.             String input = "";  
  22.             final String CLOSE_MARK = "bye";  
  23.             System.out.println("input an expression:");  
  24.             input = scanner.nextLine();  
  25.             while (input.length() != 0  
  26.                   && !CLOSE_MARK.equals((input))) {  
  27.                   System.out.print("Polish Notation (PN):");  
  28.                   try {  
  29.                         toPolishNotation(input);  
  30.                   } catch (NumberFormatException e) {  
  31.                         System.out.println("\ninput error, not a number.");  
  32.                   } catch (IllegalArgumentException e) {  
  33.                         System.out.println("\ninput error:" + e.getMessage());  
  34.                   } catch (Exception e) {  
  35.                         System.out.println("\ninput error, invalid expression.");  
  36.                   }  
  37.                   System.out.print("Reverse Polish Notation (RPN):");  
  38.                   try {  
  39.                         toReversePolishNotation(input);  
  40.                   } catch (NumberFormatException e) {  
  41.                         System.out.println("\ninput error, not a number.");  
  42.                   } catch (IllegalArgumentException e) {  
  43.                         System.out.println("\ninput error:" + e.getMessage());  
  44.                   } catch (Exception e) {  
  45.                         System.out.println("\ninput error, invalid expression.");  
  46.                   }  
  47.                   System.out.println("input a new expression:");  
  48.                   input = scanner.nextLine();  
  49.             }  
  50.             System.out.println("program exits");  
  51.       }  
  52.       /** 
  53.        * parse the expression , and calculate it. 
  54.        * @param input 
  55.        * @throws IllegalArgumentException 
  56.        * @throws NumberFormatException 
  57.        */  
  58.       private static void toPolishNotation(String input)  
  59.                   throws IllegalArgumentException, NumberFormatException {  
  60.             int len = input.length();  
  61.             char c, tempChar;  
  62.             Stack<Character> s1 = new Stack<Character>();  
  63.             Stack<Double> s2 = new Stack<Double>();  
  64.             Stack<Object> expression = new Stack<Object>();  
  65.             double number;  
  66.             int lastIndex = -1;  
  67.             for (int i=len-1; i>=0; --i) {  
  68.                   c = input.charAt(i);  
  69.                   if (Character.isDigit(c)) {  
  70.                         lastIndex = readDoubleReverse(input, i);  
  71.                         number = Double.parseDouble(input.substring(lastIndex, i+1));  
  72.                         s2.push(number);  
  73.                         i = lastIndex;  
  74.                         if ((int) number == number)  
  75.                               expression.push((int) number);  
  76.                         else  
  77.                               expression.push(number);  
  78.                   } else if (isOperator(c)) {  
  79.                         while (!s1.isEmpty()  
  80.                                     && s1.peek() != ')'  
  81.                                     && priorityCompare(c, s1.peek()) < 0) {  
  82.                               expression.push(s1.peek());  
  83.                               s2.push(calc(s2.pop(), s2.pop(), s1.pop()));  
  84.                         }  
  85.                         s1.push(c);  
  86.                   } else if (c == ')') {  
  87.                         s1.push(c);  
  88.                   } else if (c == '(') {  
  89.                         while ((tempChar=s1.pop()) != ')') {  
  90.                               expression.push(tempChar);  
  91.                               s2.push(calc(s2.pop(), s2.pop(), tempChar));  
  92.                               if (s1.isEmpty()) {  
  93.                                     throw new IllegalArgumentException(  
  94.                                           "bracket dosen't match, missing right bracket ')'.");  
  95.                               }  
  96.                         }  
  97.                   } else if (c == ' ') {  
  98.                         // ignore  
  99.                   } else {  
  100.                         throw new IllegalArgumentException(  
  101.                                     "wrong character '" + c + "'");  
  102.                   }  
  103.             }  
  104.             while (!s1.isEmpty()) {  
  105.                   tempChar = s1.pop();  
  106.                   expression.push(tempChar);  
  107.                   s2.push(calc(s2.pop(), s2.pop(), tempChar));  
  108.             }  
  109.             while (!expression.isEmpty()) {  
  110.                   System.out.print(expression.pop() + " ");  
  111.             }  
  112.             double result = s2.pop();  
  113.             if (!s2.isEmpty())  
  114.                   throw new IllegalArgumentException("input is a wrong expression.");  
  115.             System.out.println();  
  116.             if ((int) result == result)  
  117.                   System.out.println("the result is " + (int) result);  
  118.             else  
  119.                   System.out.println("the result is " + result);  
  120.       }  
  121.       /** 
  122.        * parse the expression, and calculate it. 
  123.        * @param input 
  124.        * @throws IllegalArgumentException 
  125.        * @throws NumberFormatException 
  126.        */  
  127.       private static void toReversePolishNotation(String input)  
  128.                   throws IllegalArgumentException, NumberFormatException {  
  129.             int len = input.length();  
  130.             char c, tempChar;  
  131.             Stack<Character> s1 = new Stack<Character>();  
  132.             Stack<Double> s2 = new Stack<Double>();  
  133.             double number;  
  134.             int lastIndex = -1;  
  135.             for (int i=0; i<len; ++i) {  
  136.                   c = input.charAt(i);  
  137.                   if (Character.isDigit(c) || c == '.') {  
  138.                         lastIndex = readDouble(input, i);  
  139.                         number = Double.parseDouble(input.substring(i, lastIndex));  
  140.                         s2.push(number);  
  141.                         i = lastIndex - 1;  
  142.                         if ((int) number == number)  
  143.                               System.out.print((int) number + " ");  
  144.                         else  
  145.                               System.out.print(number + " ");  
  146.                   } else if (isOperator(c)) {  
  147.                         while (!s1.isEmpty()  
  148.                                     && s1.peek() != '('  
  149.                                     && priorityCompare(c, s1.peek()) <= 0) {  
  150.                               System.out.print(s1.peek() + " ");  
  151.                               double num1 = s2.pop();  
  152.                               double num2 = s2.pop();  
  153.                               s2.push(calc(num2, num1, s1.pop()));  
  154.                         }  
  155.                         s1.push(c);  
  156.                   } else if (c == '(') {  
  157.                         s1.push(c);  
  158.                   } else if (c == ')') {  
  159.                         while ((tempChar=s1.pop()) != '(') {  
  160.                               System.out.print(tempChar + " ");  
  161.                               double num1 = s2.pop();  
  162.                               double num2 = s2.pop();  
  163.                               s2.push(calc(num2, num1, tempChar));  
  164.                               if (s1.isEmpty()) {  
  165.                                     throw new IllegalArgumentException(  
  166.                                           "bracket dosen't match, missing left bracket '('.");  
  167.                               }  
  168.                         }  
  169.                   } else if (c == ' ') {  
  170.                         // ignore  
  171.                   } else {  
  172.                         throw new IllegalArgumentException(  
  173.                                     "wrong character '" + c + "'");  
  174.                   }  
  175.             }  
  176.             while (!s1.isEmpty()) {  
  177.                   tempChar = s1.pop();  
  178.                   System.out.print(tempChar + " ");  
  179.                   double num1 = s2.pop();  
  180.                   double num2 = s2.pop();  
  181.                   s2.push(calc(num2, num1, tempChar));  
  182.             }  
  183.             double result = s2.pop();  
  184.             if (!s2.isEmpty())  
  185.                   throw new IllegalArgumentException("input is a wrong expression.");  
  186.             System.out.println();  
  187.             if ((int) result == result)  
  188.                   System.out.println("the result is " + (int) result);  
  189.             else  
  190.                   System.out.println("the result is " + result);  
  191.       }  
  192.       /** 
  193.        * calculate the two number with the operation. 
  194.        * @param num1 
  195.        * @param num2 
  196.        * @param op 
  197.        * @return 
  198.        * @throws IllegalArgumentException 
  199.        */  
  200.       private static double calc(double num1, double num2, char op)  
  201.                   throws IllegalArgumentException {  
  202.             switch (op) {  
  203.             case '+':  
  204.                   return num1 + num2;  
  205.             case '-':  
  206.                   return num1 - num2;  
  207.             case '*':  
  208.                   return num1 * num2;  
  209.             case '/':  
  210.                   if (num2 == 0) throw new IllegalArgumentException("divisor can't be 0.");  
  211.                   return num1 / num2;  
  212.             default:  
  213.                   return 0; // will never catch up here  
  214.             }  
  215.       }  
  216.       /** 
  217.        * compare the two operations' priority. 
  218.        * @param c 
  219.        * @param peek 
  220.        * @return 
  221.        */  
  222.       private static int priorityCompare(char op1, char op2) {  
  223.             switch (op1) {  
  224.             case '+': case '-':  
  225.                   return (op2 == '*' || op2 == '/' ? -1 : 0);  
  226.             case '*': case '/':  
  227.                   return (op2 == '+' || op2 == '-' ? 1 : 0);  
  228.             }  
  229.             return 1;  
  230.       }  
  231.       /** 
  232.        * read the next number (reverse) 
  233.        * @param input 
  234.        * @param start 
  235.        * @return 
  236.        * @throws IllegalArgumentException 
  237.        */  
  238.       private static int readDoubleReverse(String input, int start)  
  239.                   throws IllegalArgumentException {  
  240.             int dotIndex = -1;  
  241.             char c;  
  242.             for (int i=start; i>=0; --i) {  
  243.                   c = input.charAt(i);  
  244.                   if (c == '.') {  
  245.                         if (dotIndex != -1)  
  246.                               throw new IllegalArgumentException(  
  247.                                     "there have more than 1 dots in the number.");  
  248.                         else  
  249.                               dotIndex = i;  
  250.                   } else if (!Character.isDigit(c)) {  
  251.                         return i + 1;  
  252.                   } else if (i == 0) {  
  253.                         return 0;  
  254.                   }  
  255.             }  
  256.             throw new IllegalArgumentException("not a number.");  
  257.       }  
  258.         
  259.       /** 
  260.        * read the next number 
  261.        * @param input 
  262.        * @param start 
  263.        * @return 
  264.        * @throws IllegalArgumentException 
  265.        */  
  266.       private static int readDouble(String input, int start)  
  267.       throws IllegalArgumentException {  
  268.             int len = input.length();  
  269.             int dotIndex = -1;  
  270.             char c;  
  271.             for (int i=start; i<len; ++i) {  
  272.                   c = input.charAt(i);  
  273.                   if (c == '.') {  
  274.                         if (dotIndex != -1)  
  275.                               throw new IllegalArgumentException(  
  276.                               "there have more than 1 dots in the number.");  
  277.                         else if (i == len - 1)  
  278.                               throw new IllegalArgumentException(  
  279.                               "not a number, dot can't be the last part of a number.");  
  280.                         else  
  281.                               dotIndex = i;  
  282.                   } else if (!Character.isDigit(c)) {  
  283.                         if (dotIndex == -1 || i - dotIndex > 1)  
  284.                               return i;  
  285.                         else  
  286.                               throw new IllegalArgumentException(  
  287.                               "not a number, dot can't be the last part of a number.");  
  288.                   } else if (i == len - 1) {  
  289.                         return len;  
  290.                   }  
  291.             }  
  292.               
  293.             throw new IllegalArgumentException("not a number.");  
  294.       }  
  295.       /** 
  296.        * return true if the character is an operator. 
  297.        * @param c 
  298.        * @return 
  299.        */  
  300.       private static boolean isOperator(char c) {  
  301.             return (c=='+' || c=='-' || c=='*' || c=='/');  
  302.       }  
  303. }  


下面是程序运行结果(绿色为用户输入):

== usage ==
input the expressions, and then the program will calculate them and show the result.
input 'bye' to exit.

input an expression:
3.8+5.3
Polish Notation (PN):+ 3.8 5.3
the result is 9.1
Reverse Polish Notation (RPN):3.8 5.3 +
the result is 9.1
input a new expression:
5*(9.1+3.2)/(1-5+4.88)
Polish Notation (PN):/ * 5 + 9.1 3.2 + - 1 5 4.88
the result is 69.88636363636364
Reverse Polish Notation (RPN):5 9.1 3.2 + * 1 5 - 4.88 + /
the result is 69.88636363636364
input a new expression:
1+((2+3)*4)-5
Polish Notation (PN):- + 1 * + 2 3 4 5
the result is 16
Reverse Polish Notation (RPN):1 2 3 + 4 * + 5 -
the result is 16
input a new expression:
bye
program exits
前缀、中缀和后缀表达式详解,中缀表达式到后缀表达式的转换规则,以及后缀表达式的计算规则,附计算代码 大雾 广东人· 大雾穷横孤儿提供2398奋斗过于·1fwojei9fhgbuij李的萨科技发挥·khfbadlq穿梭在大城市的过程流程是肯定会牛逼出门时刻都回家初始模板和吃吗上课的破壁吃吗搜的看吹牛逼吃吗,搜谱大V南京m从吧水电费出生地 ... 阅读详情

相关推荐

数据结构与算法(二)——前缀、中缀、后缀表达式

前缀、中缀、后缀表达式 及 中缀、后缀的转换(Scala版)

five小点心的博客 3438

【数据结构与算法】【12】前缀表达式、中缀表达式、后缀表达式

什么是前缀表达式、中缀表达式、后缀表达式前缀表达式、中缀表达式、后缀表达式,是通过树来存储和计算表达式的三种不同方式以如下公式为例(a+(b−c))∗d( a+(b-c) )*d(a+(b−c))∗d通过树来存储该公式,可以表示为 那么问题就来了,树只是一种抽象的数据结构,它必须要通过某个形式的文本来才能存储和输入此时,就有了三种表示方法:前缀表达式、中缀表达式、后缀表达式它们分别相当于树的前序遍历、中序遍历、后序遍历,前中后指的是遍历时符号的遍历顺序前序遍历:符号 - 左操作数 - 右操作数中序遍历:左操

天天向上 Up Up Up (*^▽^*) 2万+

STM32 Boot程序实战:从启动流程到安全跳转机制解析

本文深入解析STM32 Boot程序的核心作用与安全跳转机制,涵盖启动流程、内存管理、中断向量表重定向及固件验证等关键环节。通过实战案例分享如何实现可靠的固件升级与故障回退策略,避免设备变砖风险,提升嵌入式系统稳定性。

pluto的博客 780

数据结构与算法——前缀、中缀、后缀表达式

前缀、中缀、后缀表达式

qq_50233116的博客 7874

Windows Server 2008 R2装不上VMware Tools?别急,手动安装驱动补丁的保姆级教程来了

本文提供了Windows Server 2008 R2手动安装VMware Tools驱动补丁的详细教程,解决驱动签名验证失败问题。通过获取特定补丁文件、创建安装介质、挂载虚拟机并安装补丁等步骤,帮助用户顺利完成VMware Tools安装,提升虚拟机功能与性能。

weixin_28335283的博客 468

避开RK3588开发板SDIO配置的坑:O9201SB WiFi模组接入实战指南

本文为嵌入式开发者提供了在RK3588开发板上,利用TF卡槽接入O9201SB WiFi6模组的实战指南。文章深度剖析了SDIO配置中常见的电源管理序列冲突问题,并给出了从设备树节点修改、内核编译到系统验证的完整解决方案,帮助开发者避开配置陷阱,成功实现高性能无线连接。

sprite的博客 954

前缀、中缀、后缀表达式转换详解

本篇博文主要解决一下几个问题: 1、中缀表达式 转 后缀表达式 2、中缀表达式 转 前缀表达式 3、后缀表达式 转 中缀表达式 1、中缀表达式转后缀表达式的两种方法: 假定有中缀表达式A:1 + (( 2 + 3)* 4 ) – 5,请将它转化为后缀表达式。 方法一:直接转换法 (1)首先确定表达式表达式A的运算顺序,然后加括号:((1 + (( 2 + 3)* 4 ))...

九斤 3万+

STM32F103C8T6蓝莓派用HAL库GPIO模拟SPI驱动MAX31865读取PT100温度(附完整代码)

本文详细介绍了如何在STM32F103C8T6蓝莓派开发板上使用HAL库通过GPIO模拟SPI驱动MAX31865读取PT100温度传感器的完整方案。内容包括硬件连接、CubeMX配置、GPIO模拟SPI实现、温度计算算法及常见问题排查,并附有完整代码示例,帮助开发者快速实现高精度温度测量。

weixin_30684743的博客 937

前缀、中缀、后缀表达式及简易运算实现总结

前缀、中缀、后缀表达式及简易运算实现总结

凡的博客 8141

Claude Skills:不是更聪明,而是更“像专家”的 Agent 养成方法

Claude Skills 不是在告诉 Agent“你能做什么”, 而是在约束它“你应该如何思考、如何判断、如何给结论”。

测试者家园 1294

wsl --install 不执行,显示帮助信息

在安装使用wsl的时候碰到了wsl --install 不执行,而显示帮助信息,提供了解决方案。

水滴爬呀爬 2773

前缀 中缀 后缀表达式

前缀表达式(Polish expression, 波兰表达式) 前缀表达式 前缀表达式的运算符位于操作数之前。 (3+4)×5-6 对应的前缀表达式就是 - × + 3 4 5 6。 运算过程 例如:(3+4)×5-6 对应的前缀表达式就是 - × + 3 4 5 6 , 针对前缀表达式求值步骤如下: 从右至左扫描,将6、5、4、3压入堆栈 遇到+运算符,因此弹出3和4(3为栈顶元素,4为次顶元素),计算出3+4的值,得7,再将7入栈 接下来是×运算符,因此弹出7和5,计算出7×5=35,将35入栈 最后

PurineKing之博客 4407

计算图像哈希SHA-512

上述需要将lena.jpg放在当前目录下。

计算机视觉之光 961

前缀、中缀、后缀表达式的原理与 C++ 实现

前缀表达式,也叫波兰式,运算符置于操作数之前。例如,对于简单表达式3 + 4,其前缀表达式为+ 3 4。计算时需从右向左扫描。总的来说,前缀和中缀表达式都可以转换为后缀表达式来方便的计算,需要注意的是,在计算前缀表达式时,首先将前缀表达式反转,将反转后的表达式按照计算后缀表达式的类似方法计算,但是在这里先弹出的是左操作符,后弹出的是右操作符,而计算实际的后缀表达式时,先弹出的是右操作符,后弹出的是左操作符,写代码时需要注意。

m0_58220089的博客 2351

杰理AC695N系列芯片 LED7数码管使用教程

杰理AC695N数码管使用摘要 本教程介绍了杰理AC695N芯片驱动LED7数码管的实现方法: 硬件配置:支持7/12/13脚三种数码管类型,详细说明了7脚数码管的标准段码定义和GPIO接线方式。 软件设置: 通过修改配置文件启用LED7功能 配置GPIO引脚映射(PORTC/PORTA组) 选择与硬件匹配的真值表 层次架构:包含硬件层、驱动层、UI层和应用层的完整设计,支持数字、字符和图标显示功能。 实现要点包括正确配置引脚类型、选择真值表,并通过UI风格设置为LED7模式。

qq_42014563的博客 1346

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

Python栈的应用之中缀、前缀和后缀表达式

中缀表达式:是一个通用的算术或逻辑公式表示方法, 操作符是以中缀形式处于操作数的中间(例:3 + 4)。与前缀表达式(例:+ 3 4)或后缀表达式(例:3 4 +)相比,中缀表达式不容易被电脑解析,但仍被许多程序语言使用,因为它符合人们的普遍用法。 与前缀或后缀表达式不同的是,中缀表达式中括号是必需的。计算过程中必须用括号将操作符和对应的操作数括起来,用于指示运算的次序。如:(a + b) * c...

夜空下的凝视 2623

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

前缀、中缀、后缀表达式及中缀转后缀表达式

前缀表达式:不含括号的算术表达式,而且是将运算符写在前面,操作数写在后面的表达式。求法:首先从右往左扫描表达式,从右边第一个字符判断,如果当前字符是数字,则一直到字符串的末尾再记录下来;如果是运算符,则将右边最近的两个数字串做相应的运算,以此作为一个新串并记录下来。一直扫描到最左端停止。例子:(a + b)* (c + d) :  *+ab+cd。理解:根据优先级,把数字位置不同,有那两个可以做运...

kobe_jr的博客 4638

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

数据结构与算法之前缀、中缀、后缀表达式(中缀转前缀、中缀转后缀)

中缀表达式:我们熟悉的算术表达式,如:(3+4)*5-6+8 前缀表达式(波兰表达式):机器熟悉的算术表达式,如:+ - * + 3 4 5 6 8 后缀表达式(逆波兰表达式):机器熟悉的算术表达式,如:3 4 + 5 * 6 - 8 + 1. 中缀转前缀语言描述:从右向左遍历中缀表达式,如果是数字就压入数字栈,如果是符号就压入符号栈,如果当前符号比符号栈栈顶符号优先级小则弹出栈顶符号并压入数字栈,如果当前符号比符号栈的栈顶符号优先级大或者相等则压入符号栈,如果有括号,在遍历完括号执行完上述操作.

qq_35671159的博客 2668
上一篇: 存储管理的页面置换算法
下一篇: 简述网络爬虫的系统实现
张哲BJUT
博客等级 码龄15年 151粉丝 111原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值