Interrupted Loops
leancrew.com
leancrew.com
[ 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).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)))) using Combinatorics
# Initialization
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
primes = [3, 5, 7, 11, 13, 17]
winners = []
# Loop though the permutations, collecting only prime pairs
for p in permutations(numbers)
for i in 2:9
if !(p[i-1] + p[i] in primes)
@goto nextpermutation
end
end
push!(winners, p)
@label nextpermutation
end
If I were to use a non-brute force approach I would consider computing all the hamiltonian paths of a graph where each vertex is a number and two vertices are connected only if their sum is a prime numberSomehow it went out of favor but it is actually really nice to break out of something
`[p for p in permutations(numbers) if primePairs(p)]`
You must be very young. State = bad has been a guiding principle for many decades.
Something like:
def extend(perm):
for k in range(1,11):
if k not in perm and isprime(k + perm[-1]):
yield [*perm, k]
perms = [[]]
for _ in range(10):
perms = [extend(perm) for perm in perms]
(This is just a draft, but you get the gist)