Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a tuple where each of the members are compared by an expression?

Well, here is the thing:

I have the following Haskell code, this one:

[ (a, b, c) | c <- [1..10], b <- [1..10], a <- [1..10], a ^ 2 + b ^ 2 == c ^ 2 ]

Which will returns

[(4,3,5),(3,4,5),(8,6,10),(6,8,10)]

For those who aren't familiar with this, I'll explain:

  • It returns a tuple (a,b,c), where each of these "definitions" (a,b,c) receive a list (1 up to 10) and his members are compared by the a ^ 2 + b ^ 2 == c ^ 2 ? expression (each member).

How can I do the same (one line if possible) in Python/Ruby?

P.S.: they are compared in lexicographical order.

like image 204
luizfonseca Avatar asked Aug 21 '11 07:08

luizfonseca


1 Answers

It's possible in Python with one long line and with no import. Python's list comprehensions can be used with multiple variables:

>>> [ (a, b, c) for c in range(1, 11) for b in range(1, 11) for a in range(1, 11) if a*a + b*b == c*c ]
[(4, 3, 5), (3, 4, 5), (8, 6, 10), (6, 8, 10)]
like image 59
Luke Woodward Avatar answered Sep 30 '22 18:09

Luke Woodward