Python:应用数学运算顺序来按照括号中的层次结构重新排序字符串

Nan*_*san 1 python string eval

如何使用 Python 来应用带括号的数学运算顺序对字符串进行重新排序?

让我举个例子:

"son(father(granpa)mother))" ===> "granpa father mother son"
Run Code Online (Sandbox Code Playgroud)

这个想法是使用标准数学顺序运算对原始字符串重新排序。在数学顺序运算中,括号具有最高优先级。让我用一个数学例子:

4 + (5 + (3 + 3)) = ((3 + 3) + 5 ) + 4 = 3 + 3 + 5 + 4 = 14
Run Code Online (Sandbox Code Playgroud)

编辑:这个例子只使用+,因为python总是在+之前做*,在同一个括号级别,这不是重点,重点是字符串中的顺序,因为只会连接结果重新排序。

目标是对包含变量的字符串进行重新排序,以研究操作的可能优化。我想要重新排序的字符串示例:

def xor_with_nands(a,b):
  return f"~(~(~({a} & {b}) & {a}) & ~(~({a} & {b}) & {b}))"

>> xor_with_nands(0,1)
>> ~(~(~(0 & 1) & 0) & ~(~(0 & 1) & 1))
>> eval(xor_with_nands(0,1))
>> 1
Run Code Online (Sandbox Code Playgroud)

如果有一种方法可以创建一个函数,根据括号的数学顺序(只是括号,而不是其他数学运算顺序)对字符串进行重新排序,则可以分析某些过程中的优化。

我们的目标是获得一种工具,可以按执行顺序可视化嵌套逻辑操作,以便直观地理解它们并希望简化它们。

结论:调车场算法很棒。非常感谢!

小智 5

您正在寻找调车场算法

这会将您的数学符号(也称为中缀符号)转换为计算机可以轻松处理的格式(称为后缀符号)。请参阅此处:https: //en.wikipedia.org/wiki/Shunting-yard_algorithm以获得更好的描述。

本质上,该算法会将您的表达式转换为已经正确排序的队列。

以下是来自Brilliant.org的一些伪代码:

1.  While there are tokens to be read:
2.        Read a token
3.        If it's a number add it to queue
4.        If it's an operator
5.               While there's an operator on the top of the stack with greater precedence:
6.                       Pop operators from the stack onto the output queue
7.               Push the current operator onto the stack
8.        If it's a left bracket push it onto the stack
9.        If it's a right bracket 
10.            While there's not a left bracket at the top of the stack:
11.                     Pop operators from the stack onto the output queue.
12.             Pop the left bracket from the stack and discard it
13. While there are operators on the stack, pop them to the queue
Run Code Online (Sandbox Code Playgroud)

这将允许您定义自定义运算符定义它们的优先级。