Taxicab Numbers

Paul Hankin paul.hankin at gmail.com
Thu Dec 27 19:52:32 EST 2007


On Dec 27, 9:48 pm, rgalgon <rgal... at gmail.com> wrote:
> I'm new to Python and have been putting my mind to learning it over my
> holiday break. I've been looking over the functional programming
> aspects of Python and I'm stuck trying to come up with some concise
> code to find Taxicab numbers (http://mathworld.wolfram.com/
> TaxicabNumber.html).
>
> "Taxicab(n), is defined as the smallest number that can be expressed
> as a sum of two positive cubes in n distinct ways"
>
> In Haskell something like this could easily be done with:
> cube x = x * x * x
>
> taxicab n = [(cube a + cube b, (a, b), (c, d))
>             | a <- [1..n],
>               b <- [(a+1)..n],
>               c <- [(a+1)..n],
>               d <- [(c+1)..n],
>               (cube a + cube b) == (cube c + cube d)]
>
> Output::
> *Main> taxicab 10
> []
> *Main> taxicab 12
> [(1729,(1,12),(9,10))]
> *Main> taxicab 20
> [(1729,(1,12),(9,10)),(4104,(2,16),(9,15))]
>
> I'm looking for a succinct way of doing this in Python. I've been
> toying around with filter(),map(), and reduce() but haven't gotten
> anything half-way decent yet.
>
> So, how would you implement this taxicab(n) function in Python?
> Thanks in advance :-)

Python's list comprehensions are quite similar to haskell's, so this
code can be translated almost word-for-word.

def cube(x):
    return x * x * x

def taxicab(n):
    return [(cube(a) + cube(b), (a, b), (c, d))
        for a in range(1, n + 1)
        for b in range(a + 1, n + 1)
        for c in range(a + 1, n + 1)
        for d in range(c + 1, n + 1)
        if cube(a) + cube(b) == cube(c) + cube(d)]

for n in (10, 12, 20):
    print list(taxicab(n))

--
Paul Hankin



More information about the Python-list mailing list