Skip to content

Instantly share code, notes, and snippets.

@sangmoon
Created January 18, 2022 09:16
Show Gist options
  • Save sangmoon/ae86d20d7348e258dbd652256e9f8db8 to your computer and use it in GitHub Desktop.
Save sangmoon/ae86d20d7348e258dbd652256e9f8db8 to your computer and use it in GitHub Desktop.
Sequence for sum of adjacent two number is all square number
from collections import defaultdict
from typing import Optional
def hamilton(G: dict[int, list[int]], size: int, pt: int, path: Optional[list] = None) -> Optional[list[int]]:
if not path:
path = []
# print('hamilton called with pt={}, path={}'.format(pt, path))
if pt not in path:
path.append(pt)
if len(path)==size and issquare( path[0] + path[-1]):
print(path)
return path
for pt_next in G.get(pt):
res_path = [i for i in path]
candidate = hamilton(G, size, pt_next, res_path)
if candidate is not None: # skip loop or dead end
return candidate
# print('path {} is a dead end'.format(path))
else:
# print('pt {} already in path {}'.format(pt, path))
return
# loop or dead end, None is implicitly returned
def make_graph(max: int) -> dict[int, list[int]]:
graph = defaultdict(list)
for i in range(1, max + 1):
for j in range(1, max +1):
if i != j and issquare(i + j):
graph[i].append(j)
return graph
def issquare(n:int) -> bool:
return int(n ** 0.5) ** 2 == n
if __name__ == "__main__":
max_number = 32
for i in range (1, max_number + 1):
g = make_graph(max_number)
hamilton(g, max_number, i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment