Skip to content

Instantly share code, notes, and snippets.

@Fiona-J-W
Last active April 23, 2020 21:49
Show Gist options
  • Save Fiona-J-W/cc5047e8813cca8230285bb9437ccf03 to your computer and use it in GitHub Desktop.
Save Fiona-J-W/cc5047e8813cca8230285bb9437ccf03 to your computer and use it in GitHub Desktop.
enumerate all pathes
#! /usr/bin/python3
from typing import *
from dataclasses import dataclass
@dataclass
class Node:
neighbours: List[int]
tmp: Set[Tuple[int,...]]
pathes: Set[Tuple[int,...]]
def append_tuple(t: Tuple[int,...], value: int) -> Tuple[int, ...]:
lst = list(t)
lst.append(value)
return tuple(lst)
class state:
data : List[Node]
def __init__(self, adjacency_list: List[List[int]]):
self.data = []
for node, neighbours in enumerate(adjacency_list):
self.data.append(Node(neighbours, set(),set()))
def step(self) -> None:
for i, node in enumerate(self.data):
pathes : List[Tuple[int, ...]] = []
for path in node.tmp:
pathes.append(append_tuple(path, i))
node.pathes.update(pathes)
node.tmp = set()
for neighbour_index in node.neighbours:
#print(f"adding from {i} to {neighbour_index}: {pathes}")
neighbour = self.data[neighbour_index]
neighbour.tmp.update(pathes)
neighbour.tmp.add((i,))
def run(self, n: int) -> None:
for _ in range(n):
self.step()
def finalize(self) ->None:
for i, node in enumerate(self.data):
for path in node.tmp:
node.pathes.add(append_tuple(path, i))
node.tmp = set()
def get_cycles(self, n: int) -> Generator[Tuple[int, ...],None, None] :
for i, node in enumerate(self.data):
for path in node.pathes:
if len(path) == n and path[0] == i:
yield path
def main() -> None:
graph = [[1,2],[2,3],[0,1],[0,3]]
s = state(graph)
s.run(8)
s.finalize()
for cycle in s.get_cycles(7):
print(cycle)
#print(s.data)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment