Taxicab Numbers
Terry Jones
terry at jon.es
Thu Dec 27 19:47:21 EST 2007
>>>>> "rgalgon" == rgalgon <rgalgon at gmail.com> writes:
rgalgon> I'm new to Python and have been putting my mind to learning it
rgalgon> over my holiday break. I've been looking over the functional
rgalgon> programming aspects of Python and I'm stuck trying to come up with
rgalgon> some concise code to find Taxicab numbers
rgalgon> (http://mathworld.wolfram.com/ TaxicabNumber.html).
rgalgon> "Taxicab(n), is defined as the smallest number that can be
rgalgon> expressed as a sum of two positive cubes in n distinct ways"
rgalgon> In Haskell something like this could easily be done with:
rgalgon> cube x = x * x * x
rgalgon> taxicab n = [(cube a + cube b, (a, b), (c, d))
rgalgon> | a <- [1..n],
rgalgon> b <- [(a+1)..n],
rgalgon> c <- [(a+1)..n],
rgalgon> d <- [(c+1)..n],
rgalgon> (cube a + cube b) == (cube c + cube d)]
rgalgon> I'm looking for a succinct way of doing this in Python. I've been
rgalgon> toying around with filter(),map(), and reduce() but haven't gotten
rgalgon> anything half-way decent yet.
rgalgon> So, how would you implement this taxicab(n) function in Python?
To give a fairly literal translation of your Haskell, you could just use
this:
def cube(n): return n ** 3
def taxicab(n):
n += 1
return [(cube(a) + cube(b), (a, b), (c, d))
for a in xrange(1, n)
for b in xrange(a + 1, n)
for c in xrange(a + 1, n)
for d in xrange(c + 1, n)
if cube(a) + cube(b) == cube(c) + cube(d)]
If you print the return value of this you get the same results as your
Haskell examples. I added the following to my Python file:
if __name__ == '__main__':
import sys
print taxicab(int(sys.argv[1]))
Then I see
$ time taxicab.py 20
[(1729, (1, 12), (9, 10)), (4104, (2, 16), (9, 15))]
real 0m0.098s
user 0m0.046s
sys 0m0.046s
Terry
More information about the Python-list
mailing list