June 2017
Beginner
352 pages
8h 39m
English
We have a slightly odd-looking x for x construct here because we're not applying any transformation to the filtered values; the expression in terms of x is simply x itself. There's nothing to stop us, however, from combining a filtering predicate with a transforming expression. Here's a dictionary comprehension which maps numbers with exactly three divisors to a tuple of those divisors:
>>> prime_square_divisors = {x*x:(1, x, x*x) for x in range(101) if is_prime(x)}>>> pp(prime_square_divisors){4: (1, 2, 4), 9: (1, 3, 9), 25: (1, 5, 25), 49: (1, 7, 49), 121: (1, 11, 121), 169: (1, 13, 169), 289: (1, 17, 289), 361: (1, 19, 361), 529: (1, 23, 529), 841: (1, 29, 841), 961: (1, 31, 961), 1369: (1, 37, 1369), ...Read now
Unlock full access