.
This commit is contained in:
BIN
CS1032/lecture-2023-11-23/__pycache__/crypt.cpython-310.pyc
Normal file
BIN
CS1032/lecture-2023-11-23/__pycache__/crypt.cpython-310.pyc
Normal file
Binary file not shown.
BIN
CS1032/lecture-2023-11-23/__pycache__/nqueens.cpython-310.pyc
Normal file
BIN
CS1032/lecture-2023-11-23/__pycache__/nqueens.cpython-310.pyc
Normal file
Binary file not shown.
BIN
CS1032/lecture-2023-11-23/__pycache__/pat.cpython-310.pyc
Normal file
BIN
CS1032/lecture-2023-11-23/__pycache__/pat.cpython-310.pyc
Normal file
Binary file not shown.
17
CS1032/lecture-2023-11-23/crypt.py
Normal file
17
CS1032/lecture-2023-11-23/crypt.py
Normal file
@@ -0,0 +1,17 @@
|
||||
from hashlib import sha256
|
||||
from itertools import cycle
|
||||
import base64
|
||||
|
||||
def crypt(msg: bytes, key: str) -> bytes:
|
||||
key_h = sha256()
|
||||
key_h.update(key.encode('utf8'))
|
||||
key = key_h.digest()
|
||||
|
||||
return bytes(p ^ k for (p, k) in zip(msg, cycle(key)))
|
||||
|
||||
def encrypt(msg: str, key: str) -> str:
|
||||
return base64.b64encode(crypt(bytes(msg, 'utf8'), key)).decode('utf8')
|
||||
|
||||
def decrypt(msg: str, key: str) -> str:
|
||||
return crypt(base64.b64decode(msg), key).decode('utf8')
|
||||
|
||||
19
CS1032/lecture-2023-11-23/nqueens.pl
Normal file
19
CS1032/lecture-2023-11-23/nqueens.pl
Normal file
@@ -0,0 +1,19 @@
|
||||
safe(Q1X-Q1Y, Q2X-Q2Y) :-
|
||||
between(0, 7, Q1Y),
|
||||
between(0, 7, Q2Y),
|
||||
Q1X =\= Q2X,
|
||||
Q1Y =\= Q2Y,
|
||||
abs(Q1X - Q2X) =\= abs(Q1Y - Q2Y).
|
||||
safe(_, []).
|
||||
safe(QN, [Q | QS]) :- safe(QN, [Q | QS], 1).
|
||||
safe(_, [], _).
|
||||
safe(QN, [Q | QS], QX) :- safe(0-QN, QX-Q), safe(QN, QS, QX + 1).
|
||||
|
||||
add(Qs, QsN) :-
|
||||
QsN = [Q | Qs],
|
||||
safe(Q, Qs).
|
||||
|
||||
add(1, Qs, QsN) :- add(Qs, QsN).
|
||||
add(N, Qs, QsN) :- add(Qs, QA), add(M, QA, QsN), succ(M, N).
|
||||
|
||||
solution(Qs) :- add(8, [], Qs).
|
||||
18
CS1032/lecture-2023-11-23/nqueens.py
Normal file
18
CS1032/lecture-2023-11-23/nqueens.py
Normal file
@@ -0,0 +1,18 @@
|
||||
def safe(q1, q2):
|
||||
(q1x, q1y) = q1
|
||||
(q2x, q2y) = q2
|
||||
return q1x != q2x and q1y != q2y and abs(q1x - q2x) != abs(q1y - q2y)
|
||||
|
||||
def possible_positions(current, n):
|
||||
return ((*current, y) for y in range(n) if all(safe((len(current), y), q) for q in enumerate(current)))
|
||||
|
||||
def solutions_r(current, n = 8):
|
||||
if len(current) == n:
|
||||
yield current
|
||||
return
|
||||
|
||||
for pos in possible_positions(current, n):
|
||||
yield from solutions_r(pos, n)
|
||||
|
||||
def solutions(n = 8):
|
||||
return solutions_r((), n)
|
||||
7
CS1032/lecture-2023-11-23/pat.py
Normal file
7
CS1032/lecture-2023-11-23/pat.py
Normal file
@@ -0,0 +1,7 @@
|
||||
def l(n=9):
|
||||
for x in range(1, n):
|
||||
print(" " * (x % 2), "*")
|
||||
|
||||
def r(n=5):
|
||||
for x in range(n, -1, -1):
|
||||
print("*" * (x * 2 + 1))
|
||||
Reference in New Issue
Block a user