1

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.

Pycz
  • 366
  • 3
  • 12
  • 1
    you should check http://codereview.stackexchange.com/ – root Oct 14 '12 at 22:53
  • This code is too long, try and give a [Short, Self Contained, Correct (Compilable), Example](http://sscce.org/) :) – Andy Hayden Oct 14 '12 at 22:59
  • It's not so easy, I can say, that all functions (I think that _simple_div too) are correct, especially then it runs step-by step. Can I ask you only to test my code using debugger and simply run it and say me results? Just put a breakpoint on line 383 and then go in the _simple_div method. – Pycz Oct 14 '12 at 23:10

1 Answers1

0

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.

DSM
  • 342,061
  • 65
  • 592
  • 494
  • Thanks! I'm paste `if i==-1: i=0` but it was a hack, hm, I'm blind man, I paste it in wrong place! Thanks very much! I'll do a real copy method. – Pycz Oct 15 '12 at 00:35