division by 7 efficiently ???
Steven D'Aprano
steve at REMOVEME.cybersource.com.au
Wed Jan 31 22:11:32 EST 2007
On Wed, 31 Jan 2007 18:42:54 -0800, krypto.wizard wrote:
> How to divide a number by 7 efficiently without using - or / operator.
> We can use the bit operators. I was thinking about bit shift operator
> but I don't know the correct answer.
I'd be surprised if there was a trick for dividing by seven efficiently...
it is one of the "difficult" cases. See:
http://www.bitwisemag.com/copy/wilf/wilf5.html
for a discussion.
But even if there is some nifty algorithm for efficiently dividing by
seven using bit operators, I don't expect it will work efficiently in
Python. The overhead of using objects will probably outweigh any saving
you might get by using magic tricks, so you should just use division.
It is like using the XOR trick for swapping integers: there's just no
point in doing it in Python except as a trick, because it is slower than
just swapping them:
>>> timeit.Timer("x = x^y; y = x^y; x= x^y", "x, y = 1, 2").repeat()
[0.88827300071716309, 0.85192012786865234, 0.81278204917907715]
>>> timeit.Timer("x, y = y, x", "x, y = 1, 2").repeat()
[0.71292495727539062, 0.65545105934143066, 0.68413901329040527]
--
Steven D'Aprano
More information about the Python-list
mailing list