1 | initial version |
Something like that has very recently been added to Python 3, in the form of "expression assignment" :=, but that would only help you once sage has migrated to Python 3. There is a workaround by using nested "for" clauses in list or iterator comprehensions:
w=[n for n in prime_range(5,100) for m in [pp(n)] for k in [pp(m)] if (n+m+k).is_prime() ];
I would not recommend it in this case because using "previous_prime" is a very expensive way of getting the previous prime if you're enumerating them in order anyway!
Given that prime_range returns a list anyway, there's no problem using it as such. If it were an iterator that lazily produces the values, there'd be a benefit in processing the generator to produce a sliding window:
from collections import deque
def iter_window(iterable,n):
T=iter(iterable)
result=deque(next(T) for i in range(n))
yield tuple(result)
for t in T:
result.popleft()
result.append(t)
yield tuple(result)
so that you can do
w=[n for k,m,n in iter_window(prime_range(2,100),3) if (n+m+k).is_prime()]
2 | No.2 Revision |
Something like that has very recently been added to Python 3, in the form of "expression assignment" :=, but that would only help you once sage has migrated to Python 3. There is a workaround by using nested "for" clauses in list or iterator comprehensions:
w=[n for n in prime_range(5,100) for m in [pp(n)] for k in [pp(m)] if (n+m+k).is_prime() ];
I would not recommend it in this case because using "previous_prime" is a very expensive way of getting the previous prime if you're enumerating them in order anyway!
Given that prime_range returns a list anyway, there's no problem using it as such. If it were an iterator that lazily produces the values, there'd be a benefit in processing the generator to produce a sliding window:
from collections import deque
def iter_window(iterable,n):
T=iter(iterable)
result=deque(next(T) result=deque((next(T) for i in range(n))
range(n)),n)
yield tuple(result)
for t in T:
result.popleft()
# the deque has max length n, so appending an
# element automatically drops the leftmost entry.
result.append(t)
yield tuple(result)
so that you can do
w=[n for k,m,n in iter_window(prime_range(2,100),3) if (n+m+k).is_prime()]