首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何替换python中的阶乘、nCr和nPr操作?

如何替换python中的阶乘、nCr和nPr操作?
EN

Stack Overflow用户
提问于 2020-06-19 03:33:18
回答 1查看 312关注 0票数 0

无论何时,我都想要:

我写的是“!”它会将符号更改为“math.factorial”

当我编写C时,它会执行choose (nCr)操作(n! / (r! (n - r)! ))

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

这是我开始写的代码:

代码语言:javascript
运行
复制
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)

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

你能帮帮我吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-19 19:22:25

以下是您可以执行的操作:

代码语言:javascript
运行
复制
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中。

然后将输入行中的所有匹配项替换为所需的部分。运行此命令将生成以下输出:

代码语言:javascript
运行
复制
2*x + math.factorial(9-5) + math.factorial(99) + math.factorial(max) + math.factorial(x-3) -4

对于其他运算符,也可以采用类似的方法。

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

代码语言:javascript
运行
复制
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)

它创建输出:

代码语言:javascript
运行
复制
2*x + math.factorial(9-5) + math.factorial(99) + math.factorial(max) + math.factorial(x-3) -4 * math.factorial((7 + math.factorial(2)))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62458011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档