Commit 4b8241b9 authored by Vít Novotný's avatar Vít Novotný
Browse files

added example 2.3_5

parent 26f8ab79
% nacteni:
/* ['2.3_5.pl']. */
del1(A,[A|T],T).
del1(A,[H|T1],[H|T2]) :- del1(A,T1,T2).
insert(A,L,[A|L]).
insert(A,[H|T1],[H|T2]):- insert(A,T1,T2).
perm1([],[]).
perm1([H|T],L):- perm1(T,V), insert(H,V,L).
perm2([],[]).
perm2(L,[X|P]) :- del1(X,L,L1),perm2(L1,P).
perm3([],[]).
perm3(L,[H|T]):- append(A,[H|B],L),append(A,B,L1), perm3(L1,T).
% demonstracni vypis
% abychom se vyhli varovanim "Redefined static procedure ..."
:- dynamic
write_all_X/3,
start/0.
write_all_X(Goal,X,Name):-
call(Goal),write(' '),write(Name),write(' = '),write(X),nl,fail.
write_all_X(_,_,_).
start:-
write('Prace se seznamy - permutace'),nl,
write('-------------------------------'),nl,
write('perm1 napsany pomoci insert, vysledek volani "perm1([1,2,3],L)" :'),
nl, write_all_X(perm1([1,2,3],L), L, 'L'),nl,
write('Pro blizsi porozumneni si vyzkousejte perm1, perm2 (reseny '), nl,
write('pomoci del1) a perm3 (s append) s trasovanim, napr. takto:'), nl,
write('trace, perm1([1,2,3],L).'),nl,
write('Pozn.: Po vypsani prvniho vysledku si dalsi vyzadate stisnutim ";"').
?-start.
:- retractall(write_all_X/3).
:- retractall(start/0).
#!/usr/bin/env python
# encoding=utf-8 (pep 0263)
def del1_anyX(xs):
result_head = []
result_tail = xs
for x in xs:
result_tail = result_tail[1:]
yield (x, result_head + result_tail)
result_head.append(x)
def insert(x, ys):
if not ys:
yield [x]
else:
result_head = []
result_tail = ys
for y in ys:
yield result_head + [x] + result_tail
result_tail = result_tail[1:]
result_head.append(y)
yield ys + [x]
def perm1(xs):
if not xs:
yield []
else:
for ys in perm1(xs[1:]):
for zs in insert(xs[0], ys):
yield zs
def perm2(xs):
if not xs:
yield []
else:
for y, ys in del1_anyX(xs):
for zs in perm2(ys):
yield [y] + zs
def perm3(xs):
if not xs:
yield []
else:
result_head = []
result_tail = xs
for x in xs:
result_tail = result_tail[1:]
for ys in perm3(result_head + result_tail):
yield [x] + ys
result_head.append(x)
# demonstracni vypis
if __name__ == "__main__":
print("Prace se seznamy - permutace")
print("-------------------------------\n")
print("perm1 napsany pomoci insert")
print("Vysledek volani perm1([1, 2, 3]): %s\n" % \
list(perm1([1, 2, 3])))
print("perm2 napsany pomoci del1_anyX")
print("Vysledek volani perm2([1, 2, 3]): %s\n" % \
list(perm2([1, 2, 3])))
print("perm3 napsany pomoci pruchodu seznamem")
print("Vysledek volani perm3([1, 2, 3]): %s\n" % \
list(perm3([1, 2, 3])))
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment