#!/usr/bin/env python
# encoding=utf-8 (pep 0263)
from linked_lists import LinkedList, Cons, Nil, member, member_anyX
def path(a, z, graph):
for cesta in path1(a, LinkedList([z]), graph, 1):
yield cesta
def path1(a, akumulator_cesty, graph, depth):
if akumulator_cesty.head == a:
yield akumulator_cesty
else:
y = akumulator_cesty.head
for x in adjacent_anyX(y, graph):
if not member(x, akumulator_cesty):
for cesta in path1(a, Cons(x, akumulator_cesty), graph, depth+1):
yield cesta
def adjacent_anyX(y, graph):
_, edges = graph
for a, b in member_anyX(edges):
if y == a:
yield b
if y == b:
yield a
_graph = (LinkedList(["a", "b", "c", "d"]),
LinkedList([("a", "b"), ("b", "d"), ("b", "c"), ("c", "d")]))
# demonstracni vypis
if __name__ == "__main__":
print('Cesta v grafu\n')
print('next(path("a", "c", _graph)) : %s' % next(path("a", "c", _graph)))
Cesta v grafu
next(path("a", "c", _graph)) : ['a', 'b', 'c']
| % nacteni:
/* ['2.9.1_21.pl']. */
path(A,Z,Graph,Cesta) :- path1(A,[Z],Graph,Cesta).
path1(A,[A|Cesta1],_,[A|Cesta1]).
path1(A,[Y|Cesta1],Graph,Cesta) :- adjacent(X,Y,Graph),
\+ member(X,Cesta1),path1(A,[X,Y|Cesta1],Graph,Cesta).
adjacent(X,Y,graph(_,Edges)) :- member(e(X,Y),Edges)
;member(e(Y,X),Edges).
graph([a,b,c,d],[e(a,b),e(b,d),e(b,c),e(c,d)]).
% demonstracni vypis
start:-
write('Cesta v grafu'),nl, nl,
write('path(a, c, graph, Cesta) : '),
graph(Nodes,Edges),
path(a, c, graph(Nodes,Edges), Cesta),
write(Cesta), nl, nl.
?-start.
Cesta v grafu
path(a, c, graph, Cesta) : [a,b,c]
|