python - 如何在 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)
这也应该通过nCr
andnPr
操作来完成。
你能帮助我吗?
解决方案
这是您可以执行的操作:
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)))
推荐阅读
- angular - 从地理编码器获取地址,如自动完成谷歌地图
- android - 处理 JSON 响应 - 基于响应的相同属性的 JsonArray 和 JsonObject - Java - Android Retrofit
- php - 在 PHP 中基于专家级字符串创建数组
- javascript - jQuery循环遍历对象
- java - 使用 Java Microsoft graph SDK 在 Outlook 中添加成员
- java - java - 如何在java中找到2D ArrayList的列的唯一值?
- jquery - Jquery 显示隐藏切换
- c# - C# - 由线程回调运行的定时器只运行一次
- php - 带有一些选项的数组差异
- javascript - 无法使用super调用继承的类函数