Advanced · Comprehensions · 184 of 264
Pythagorean triples
Find all triples a < b < c up to n with a*a + b*b == c*c, using a list comprehension. Print them ordered by a, then b.
Input: n (5 to 60). Output: one triple per line.
Examples
Input
15
Output
3 4 5 5 12 13 6 8 10 9 12 15
Input
5
Output
3 4 5
One more test checks other inputs when you press Check.
Stuck? The idea behind comprehensions
A comprehension builds a list in one line: [x * x for x in range(5)]. Add if to keep only some: [x for x in nums if x > 0].
The same works for sets {…} and dictionaries {key: value for …}.
nums = [int(x) for x in input().split()] print([x * x for x in nums if x % 2 == 0])
Watch for: Clear first, short second: when a comprehension needs two ifs and two fors, a loop reads better.