Stack Overflow Asked by Titan on December 1, 2020
I wrote a python program that generates random mathematical strings, such as "2+3**4/3"
and "3**3**50-2"
, and then uses eval()
to compute them.
Computing "2+3**4/3"
will work fine but evaluating "3**3**50-2"
will take too long since it will be a very large number. I need to check if the power will be too large to compute before it tries, or I need to terminate the function after a certain amount of time.
Since this function needs to be run tens of thousands of times, efficiency is very important
I’ve tried using the "multiprocessing" and "threading" libraries to terminate the thread if it takes over a second, but these solutions slow down the program too much.
Any suggestions? I’m completely stumped on this one. Thanks.
I found a fast and simple solution to this problem:
try:
eval("math.pow(a,b)")
except:
print("too long to compute")
Instead of using **
I used math.pow
so it returns an overflow error if 'a' and 'b' are too large. Then the exception can be handled with a try-except statement.
Correct answer by Titan on December 1, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP