4 ms·
You can of course always do it with a list comprehension, also: [ seq for seq in permutations(range(1,10)) if all(x + y in primes
by oisdk 6y ago
You can of course always do it with a list comprehension, also:
[ seq
for seq in permutations(range(1,10))
if all(x + y in primes
for x, y in zip(seq, islice(seq, 1, None))) ]
This has the same short-circuiting behaviour as the loop-based solution (i.e. it will break out of the inner loop appropriately).
- pdonis 6y agoYou could use the all function instead of the inner loop in the for-loop solution as well, which would solve the problem without any of the kludges described in the article. But I like the list comprehension better since it is more declarative.
- heisenzombie 6y agoAgree. The sort of python user who regularly writes stuff like zip(seq, islice(seq, 1, None))) may enjoy the `itertoolz` library https://github.com/pytoolz/toolz which (among many other handy functions) has a sliding_window function: def sliding_window(n, seq): """ A sequence of overlapping subsequences >>> list(sliding_window(2, [1, 2, 3, 4])) [(1, 2), (2, 3), (3, 4)] """ return zip(*(collections.deque(itertools.islice(it, i), 0) or it for i, it in enumerate(itertools.tee(seq, n))))