The below piece of code is aimed at converting a factorial into its products. E.g. "4!" --> "(4*3*2*1)". This code does not work due to the line exec(codeToRun). However, if I instead put the value of codeToRun in place of exec(codeToRun) then it works perfectly so why doesn't exec work?
Doesn't work ↓
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
Does work ↓
def checkSpecialChars(char, stringToCheck, codeToRun):
while char in stringToCheck:
currentString=""
for i in range(len(stringToCheck)):
if stringToCheck[i]==char:
try:
eval(codeToRun)
except:
stringToCheck = stringToCheck[:i-len(currentString)] + "(" + "*".join(str(integer) for integer in range(int(currentString),0,-1)) + ")" + stringToCheck[i+1:]
print(stringToCheck)
currentString=""
break
if stringToCheck[i].isdigit():
currentString+=stringToCheck[i]
else:
currentString=""
return stringToCheck
EDIT #1 The number of factorials can be more than one and the number of digits in each factorial can be more than one as well.
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)"
EDIT #2
I have added a print statement outputting the string as seen in the two pieces of code. Now when I run the program and enter 4!, the program pauses (as if it was an infinite loop). I then press CTRL+C to exit the program and it decides to output 4!. This then happens every time I press CTRL+C so the line must be running because the print statement occurs but it remains at 4!.
'4!'the only test case you have? Is there only ever a single factorial per string with the format of digit(s) and then a single'!'character?"51!/50!"is a possibility.