December 2018
Beginner to intermediate
796 pages
19h 54m
English
We can apply filtering to a comprehension. Let's do it first with filter. Let's find all Pythagorean triples whose short sides are numbers smaller than 10. We obviously don't want to test a combination twice, and therefore we'll use a trick similar to the one we saw in the previous example:
# pythagorean.triple.pyfrom math import sqrt# this will generate all possible pairsmx = 10triples = [(a, b, sqrt(a**2 + b**2)) for a in range(1, mx) for b in range(a, mx)]# this will filter out all non pythagorean triplestriples = list( filter(lambda triple: triple[2].is_integer(), triples))print(triples) # prints: [(3, 4, 5.0), (6, 8, 10.0)]
Read now
Unlock full access