首页 > 解决方案 > 如何在 python 中替换阶乘、nCr 和 nPr 操作?

问题描述

我想在任何时候:

我写 '!' 它将符号更改为“math.factorial”

当我写C它时,它会选择(nCr)操作(n! / (r! (n - r)! )

如果我写P它,它会进行置换 ( nPr) 操作 ( n! / (n - r)!)

这是我开始写的代码:

import math
term = ['math.factorial']
replace = ['!']
a = input('')
for word in replace:
    a = a.replace(word, term[replace.index(word)])

print(a)

这段代码将改变'!' 到“math.factorial”,以便我能够使用阶乘运算进行计算。但是,我希望能够在数字之前移动“math.factorial”。

前任。

这就是我的程序所做的:

如果我输入2*x + (9-5)!

我的程序将打印2*x + (9-5)math.factorial

前任。

它应该这样做:

如果我输入2*x + (9-5)!

我的程序将打印2*x + math.factorial(9-5)

这也应该通过nCrandnPr操作来完成。

你能帮助我吗?

标签: pythonmathreplace

解决方案


这是您可以执行的操作:

import re

input_line = "2*x + (9-5)! + 99! + max! + (x-3)! -4"

pattern = "\(.+?\)(?=!)|[0-9]+(?=!)|[a-z]+(?=!)"
result = re.findall(pattern, input_line)
print(result)
output_line = input_line
for match in result:
    if match[0] == '(':
        output_line = output_line.replace(f"{match}!", f"math.factorial{match}")
    else:
        output_line = output_line.replace(f"{match}!", f"math.factorial({match})")

print(output_line)

它首先创建一个正则表达式"\(.*?\)(?=!)| [0-9]*(?=!)| [a-z]*(?=!)" ,然后与输入行匹配。所有匹配项都存储在result.

然后,您将输入行中的所有匹配项替换为所需的部分。运行它会产生输出:

2*x + math.factorial(9-5) + math.factorial(99) + math.factorial(max) + math.factorial(x-3) -4

您可以对其他运营商进行类似的操作。

编辑:我无法阻止自己尝试更多。这更接近于一个好的解决方案,但仍然存在缺陷。

import re

input_line = "2*x + (9-5)! + 99! + max! + (x-3)! -4 * ((7 + 2!)!)"
pattern_1 = "[0-9]+(?=!)"
pattern_2 = "[a-z]+(?=!)"
pattern_3 = "\(.+?\)(?=!)"
result_1 = re.findall(pattern_1, input_line)

output_line = input_line
result_3 = re.findall(pattern_3, output_line)

for match in result_3:
    output_line = output_line.replace(f"{match}!", f"math.factorial{match}")
for match in result_1:
    output_line = output_line.replace(f"{match}!", f"math.factorial({match})")
result_2 = re.findall(pattern_2, input_line)
for match in result_2:
    output_line = output_line.replace(f"{match}!", f"math.factorial({match})")
result_3 = re.findall(pattern_3, output_line)

print(output_line)

它创建输出:

2*x + math.factorial(9-5) + math.factorial(99) + math.factorial(max) + math.factorial(x-3) -4 * math.factorial((7 + math.factorial(2)))

推荐阅读