-1

I have a program :

def mid(a, b):
    if a == 0:
        print(b)
        r = b
        r = r + 1
        return r
    while b != 0:
        if a > b:
            a = a - b


    print(a)
    r = a
    return r

So I wanna use exec function to execute this program, like that :

exec('%s(*(tests[i]))' % funName)

with funName is "mid", tests[i] = (3,2) so when (a,b) = (3,2) the while loop become infinite loop and I can't get out of this loop at exec . Any suggest for me ?

Phạm Ân
  • 175
  • 2
  • 10

1 Answers1

1

This has nothing to do with exec, your function just has a bug which causes an infinite loop.

You can see what your function is doing using snoop:

from snoop import snoop

@snoop
def mid(a, b):
    ...

mid(3, 2)

Output:

.. a = 3
.. b = 2
 | def mid(a, b):
 |     if a == 0:
 |     while b != 0:
 |         if a > b:
 |             a = a - b
.............. a = 1
 |     while b != 0:
 |         if a > b:
 |     while b != 0:
 |         if a > b:
 |     while b != 0:
...
etc.

a = 1 and b = 2, so b != 0 is always True, a > b is always False, and nothing changes.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
  • yea I mean my infinite loop is my input of exec() so I wanna find a way to terminate exec() when exec() react a test case to make the loop is an infinite loop – Phạm Ân Apr 08 '20 at 16:01
  • @PhạmÂn there's nothing special about exec in this situation. `exec("f()")` is exactly equivalent to just `f()`. It doesn't provide any extra tools for early termination. If your code isn't the issue and you want to know how to terminate some unknown code early, try https://stackoverflow.com/questions/492519/timeout-on-a-function-call. – Alex Hall Apr 08 '20 at 16:11