Sage List comprehension
[expression for element in iterable_thing]
This creates a list which contains the expression for every element of iterable_thing. An iterable thing is a list for example, like a list created with the range function.
[expression if condition for element in iterable_thing]
Similar to the previous one, except only the elements for which the condition holds will be included.
[expression if condition1 else expression_alt for element in iterable_thing1 for element2 in iterable_thing2 ... for elementN in iterable_thingN]
We can write multiple fors.
[n^2 for n in range(1, 5)] # [1, 4, 9, 16] [n for n in [-1, 2, -3, 4] if n > 0] # [2, 4]
What do these do?
Execute the following, and then study how they work.
[n for n in range(1, 10)]
[(n, m) for n in range(1, 10) for m in range(1, 5)]
[n for n in range(1, 10) if is_prime(n)]
[n for n in range(1, 100) if n % 5 == 0 and n % 7 == 1]
[(n, m) for n in range(1, 5) for m in range(n, 5)]
[(m, n) for n in range(1, 10) for m in range(n, 10) if m % n == 0]
sorted([(m, n) for n in range(1, 10) for m in range(n, 10) if m % n == 0])
sum([n for n in range(1, 10) if is_prime(n)])
A little spoiler for the following: spoiler
[n for n in range(1, 100) if n == sum([m for m in range(1, n) if n % m == 0])]
Solve the followings
- Find the square numbers x below 1000, where x + 1 is a prime. For example 4. (Find all of these numbers.)
- Find those (x, y) pairs of numbers, where both are prime and their integer division (//) is prime as well. For example (11, 2).
- Find the 3 digit numbers with the form xyz, where xyz (= 100 * x + 10 * y + z) = x^3 + y^3 + z^3. For example 1, 5, 3, because 13 + 53 + 33 = 153.
- Find the numbers below 10000, which can be written as the sum of 2 cube numbers in two different ways.
- Find the first 10 derivative of cos(x)sin(x)x2, including the 0th derivative, evaluated at 0, as an 11 long list.
- Plot the previous function and its derivatives on a plot on the interval [ − 2π,2π]