How do I find out if a power will take too long to compute? (Python)

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.

One Answer

I found a fast and simple solution to this problem:

    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

Add your own answers!

Related Questions

Pandas dataframe only select the columns that have all True

2  Asked on December 11, 2020 by learningisfun


I want to create fixed sidebar but scroll does not work

5  Asked on December 11, 2020 by nav


How can I extract all PDF Tags related to content with Python?

2  Asked on December 11, 2020 by martin-thoma


React Fizz-Buzz

2  Asked on December 11, 2020 by kamil-kos


Update Subform based on Form Combo Box

0  Asked on December 10, 2020 by hazat-bangurah


Determine if __getattr__ is method or attribute call

3  Asked on December 10, 2020 by robin-orheden


How to implement category axis in matplotlib?

0  Asked on December 10, 2020 by fgg1991


Pre-fill the checkbox with url

2  Asked on December 10, 2020 by sevenine


Shell=false generates OsError

1  Asked on December 10, 2020 by azza-abidi


LINQ query orderBy a subquery

2  Asked on December 9, 2020 by golfbravo


Ask a Question

Get help from others!

© 2022 All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir