Skip to content

Instantly share code, notes, and snippets.

@Hermann-SW
Last active September 23, 2023 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hermann-SW/19d429787d7f8e4cf43cd04e8345868e to your computer and use it in GitHub Desktop.
Save Hermann-SW/19d429787d7f8e4cf43cd04e8345868e to your computer and use it in GitHub Desktop.
Find permutations of numbers 1..N with each successive pair summing to a square
# pylint: disable=C0103, R1728
# invalid-name, consider-using-generator
""" blacked and pylinted; https://mersenneforum.org/showthread.php?t=22915 """
import sys
from sys import argv, stderr
from math import isqrt
N = 15 if len(argv) < 2 else int(argv[1])
a = [[] for i in range(N + 1)]
stop = len(argv) >= 3
def is_square(i):
"""silence pylint"""
return i == isqrt(i) ** 2
def populate(A):
"""poulate adjacency list"""
for sq in range(2, 2 * N):
if is_square(sq):
for v in range(max(sq - N, 1), min(N + 1, sq)):
if v != sq - v:
A[v].append(sq - v)
def srch(A, seen, v, cnt, sol):
"""recursive search at nove v"""
seen[v] = True
cnt[0] += 1
sol.append(v)
if cnt[0] == N:
print(sol)
if stop:
sys.exit()
else:
for w in A[v]:
if not seen[w]:
srch(A, seen, w, cnt, sol)
cnt[0] -= 1
seen[v] = False
sol.pop()
populate(a)
print("average vertex degree:", sum([len(l) for l in a]) / N, file=stderr)
for s in range(N + 1):
if a[s] != []:
srch(a, [False for i in range(N + 1)], s, [0], [])
@Hermann-SW
Copy link
Author

Hermann-SW commented Sep 23, 2023

https://mersenneforum.org/showthread.php?p=638895#post638895

$ black nsum.py 
All done! ✨ 🍰 ✨
1 file left unchanged.
$ pylint nsum.py 

--------------------------------------------------------------------
Your code has been rated at 10.00/10 (previous run: 10.00/10, +0.00)

$ python nsum.py 
average vertex degree: 2.0
[8, 1, 15, 10, 6, 3, 13, 12, 4, 5, 11, 14, 2, 7, 9]
[9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8]
$ python nsum.py 23
average vertex degree: 2.4347826086956523
[2, 23, 13, 12, 4, 21, 15, 10, 6, 19, 17, 8, 1, 3, 22, 14, 11, 5, 20, 16, 9, 7, 18]
[9, 16, 20, 5, 11, 14, 22, 3, 1, 8, 17, 19, 6, 10, 15, 21, 4, 12, 13, 23, 2, 7, 18]
[18, 7, 2, 23, 13, 12, 4, 21, 15, 10, 6, 19, 17, 8, 1, 3, 22, 14, 11, 5, 20, 16, 9]
[18, 7, 9, 16, 20, 5, 11, 14, 2, 23, 13, 12, 4, 21, 15, 10, 6, 19, 17, 8, 1, 3, 22]
[18, 7, 9, 16, 20, 5, 11, 14, 22, 3, 1, 8, 17, 19, 6, 10, 15, 21, 4, 12, 13, 23, 2]
[22, 3, 1, 8, 17, 19, 6, 10, 15, 21, 4, 12, 13, 23, 2, 14, 11, 5, 20, 16, 9, 7, 18]
$ time python nsum.py 45 stop
average vertex degree: 3.5555555555555554
[1, 3, 6, 10, 15, 21, 28, 8, 17, 32, 4, 5, 11, 14, 35, 29, 20, 44, 37, 12, 13, 36, 45, 19, 30, 34, 2, 7, 18, 31, 33, 16, 9, 27, 22, 42, 39, 25, 24, 40, 41, 23, 26, 38, 43]

real	0m1.430s
user	0m1.424s
sys	0m0.003s
$ 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment