My Python code return different answers when it runs and when it is in step-by-step debugging [closed]

StackOverflow https://stackoverflow.com/questions/12887338

  •  07-07-2021
  •  | 
  •  

Question


I try to write some code on Python2.7, which will able to implement a bignum arithmetic, using linear lists. I know, this is useless in Python, but it's my homework in collage. I write some working pieces of code, but problem is in dividing. I'm sure that function works, but when I run code to test it, I just get wrong answer (in some cases). But if I execute code step-by-step, it works correctly.

I'm using linux, but I tested my code on my friend's windows computer, and I got the same problem. I wrote code in Eclipse with PyDev, if it is matter.

My code on Ideone: Code

If lines in console output are the same - output is correct. On Ideone output is incorrect too. But if you put a breakpoint on line 383 and then go in the _simple_div method, answer will be correct

I hope you help me to find a reason of this.
P.S. Sorry for ugly code.

Was it helpful?

Solution

If I run your code, I get

~/coding:$ python divbug2.py 
1-1
10

That -1 doesn't look right. Is there a -1 being inserted somewhere in the division? First thing to try is to search for -1 in that function, which gives

        i-=1
        res._addFirst(i)
        if i==-1: i=0

.. and that looks strange, because if i == -1, then you've just added it to res. Maybe we should check first, i.e.

        i-=1
        if i==-1: i=0
        res._addFirst(i)

Swapping those two lines produces

~/coding:$ python divbug2.py 
10
10

And then -- after writing a real .copy() method, because copy.deepcopy was really slow and even using PyPy I got bored waiting for things to finish:

>>>> all(int(str(LongNum(x)._simple_div(LongNum(y)))) == x/y for x in range(2000) for y in range(1, 2000))
True

I'm not sure why this was working for you when you did it step-by-step, but I'm a little surprised it worked at all.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top