On 1/21/2016 3:39 AM, Shiyao Ma wrote:

I wanna simulate C style integer division in Python3.

There are two problems with this spec: it assumes that 'C style integer division' is well defined and that we know the definition. Better:

"How do I write a function 'div' in Python 3 so that the following (with values added after each '==') is True:

all((div(1,2) == , div(-1,-2) == , dif(-1,2) == , dif(1,-2) == ))"

For '//', the values would be 0, 0, -1, -1. If you want 0, 0, 0, 0 (truncation toward 0), then

def div(i, j):
    return (i // j) + ((i < 0) ^ (j <  0))

print(all((div(1,2) == 0, div(-1,-2) == 0,
           div(-1,2) == 0, div(1,-2) == 0)))

prints 'True'.

--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to