无论何时,我都想要:
我写的是“!”它会将符号更改为“math.factorial”
当我编写C
时,它会执行choose (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
和nPr
操作来完成。
你能帮帮我吗?
发布于 2020-06-19 19:22:25
以下是您可以执行的操作:
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)))
https://stackoverflow.com/questions/62458011
复制相似问题