下面的代码旨在将阶乘转换为它的乘积。E、 g."4!"
-->;"(4*3*2*1)"
。由于exec(codeToRun)
行,此代码无法工作。但是,如果我用codeToRun
代替exec(codeToRun)
,那么它就完美地工作了,那么{
不起作用↓
def checkSpecialChars(char, stringToCheck, codeToRun):
while char in stringToCheck:
currentString=""
for i in range(len(stringToCheck)):
if stringToCheck[i]==char:
try:
eval(codeToRun)
except:
exec(codeToRun)
print(stringToCheck)
currentString=""
break
if stringToCheck[i].isdigit():
currentString+=stringToCheck[i]
else:
currentString=""
return stringToCheck
有效↓
^{pr2}$编辑1 阶乘的数目可以多于一个,每个阶乘中的位数也可以超过一个。在
Input:
"11!/10!"
Expected Output:
"(11*10*9*8*7*6*5*4*3*2*1)/(10*9*8*7*6*5*4*3*2*1)"
编辑2
我添加了一个输出字符串的print语句,如两段代码所示。现在,当我运行程序并输入4!
时,程序会暂停(好像它是一个无限循环)。然后我按CTRL+C
退出程序,它决定输出4!
。然后每次我按CTRL+C
时都会发生这种情况,因此该行必须在运行,因为print语句出现了,但它仍然位于4!
。在
让我们快速浏览一下文档:
以及
最后一句话似乎能解释你的烦恼。在
更具体地说,您使用一个参数调用exec,因此它将在globals()之上的locals()默认环境中执行。重要的是要认识到,这些并不一定与实际的全局和局部范围相同,但理论上可能是代理或副本或其他任何东西。现在,例如,如果您指定一个变量,这些字典中的一个会相应地更新。locals文档中的注释说明,无法保证此更新将传播到实际的本地范围。我想这就是你的程序不起作用的原因。在
如何解决这个问题:
基于以上一个简单的解决方法是
(1)与你自己订立一份合同,
codeToRun
分配给stringToCheck
。在(2)保留对传递给
exec
的locals()
实例的引用(3)使用此选项显式设置
stringToCheck
所以你的
except
块看起来有点像相关问题 更多 >
编程相关推荐