Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/cs102.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python 3.8.6
- name: Set up Python 3.9
uses: actions/setup-python@v2
with:
python-version: '3.8.6'
python-version: '3.9'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
Expand Down
2 changes: 1 addition & 1 deletion homework00/hello.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
def get_greeting(name: str) -> str:
pass
return f"Hello, {name}!"


if __name__ == "__main__":
Expand Down
24 changes: 22 additions & 2 deletions homework01/caesar.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,16 @@ def encrypt_caesar(plaintext: str, shift: int = 3) -> str:
''
"""
ciphertext = ""
# PUT YOUR CODE HERE
for i in plaintext:
if i.isalpha():
if i.isupper():
code_i = ord(i) - ord("A")
ciphertext += chr((code_i + shift) % 26 + ord("A"))
else:
code_i = ord(i) - ord("a")
ciphertext += chr((code_i + shift) % 26 + ord("a"))
else:
ciphertext += i
return ciphertext


Expand All @@ -32,8 +41,19 @@ def decrypt_caesar(ciphertext: str, shift: int = 3) -> str:
>>> decrypt_caesar("")
''
"""
# abcdefghijklmnopqrstuvwxyz
# zyxwvutsrqponmlkjihgfedcba
plaintext = ""
# PUT YOUR CODE HERE
for i in ciphertext:
if i.isalpha():
if i.isupper():
code_i = 25 - ord(i) + ord("A")
plaintext += chr(25 - (code_i + shift) % 26 + ord("A"))
else:
code_i = 25 - ord(i) + ord("a")
plaintext += chr(25 - (code_i + shift) % 26 + ord("a"))
else:
plaintext += i
return plaintext


Expand Down
40 changes: 30 additions & 10 deletions homework01/rsa.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import math
import random
import typing as tp

Expand All @@ -13,8 +14,12 @@ def is_prime(n: int) -> bool:
>>> is_prime(8)
False
"""
# PUT YOUR CODE HERE
pass
if n == 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True


def gcd(a: int, b: int) -> int:
Expand All @@ -26,8 +31,12 @@ def gcd(a: int, b: int) -> int:
>>> gcd(3, 7)
1
"""
# PUT YOUR CODE HERE
pass
while a > 0 and b > 0:
if a > b:
a %= b
else:
b %= a
return a + b


def multiplicative_inverse(e: int, phi: int) -> int:
Expand All @@ -38,8 +47,19 @@ def multiplicative_inverse(e: int, phi: int) -> int:
>>> multiplicative_inverse(7, 40)
23
"""
# PUT YOUR CODE HERE
pass

def loc_0(e, phi):
if phi == 0:
return 1, 0
(q, r) = (e // phi, e % phi)
print((q, r))
(s, t) = loc_0(phi, r)
return t, s - (q * t)

inverse = loc_0(e, phi)[0]
if inverse < 0:
inverse += phi
return inverse


def generate_keypair(p: int, q: int) -> tp.Tuple[tp.Tuple[int, int], tp.Tuple[int, int]]:
Expand All @@ -49,10 +69,10 @@ def generate_keypair(p: int, q: int) -> tp.Tuple[tp.Tuple[int, int], tp.Tuple[in
raise ValueError("p and q cannot be equal")

# n = pq
# PUT YOUR CODE HERE
n = p * q

# phi = (p-1)(q-1)
# PUT YOUR CODE HERE
phi = (p - 1) * (q - 1)

# Choose an integer e such that e and phi(n) are coprime
e = random.randrange(1, phi)
Expand All @@ -68,7 +88,7 @@ def generate_keypair(p: int, q: int) -> tp.Tuple[tp.Tuple[int, int], tp.Tuple[in

# Return public and private keypair
# Public key is (e, n) and private key is (d, n)
return ((e, n), (d, n))
return (e, n), (d, n)


def encrypt(pk: tp.Tuple[int, int], plaintext: str) -> tp.List[int]:
Expand All @@ -85,7 +105,7 @@ def decrypt(pk: tp.Tuple[int, int], ciphertext: tp.List[int]) -> str:
# Unpack the key into its components
key, n = pk
# Generate the plaintext based on the ciphertext and key using a^b mod m
plain = [chr((char ** key) % n) for char in ciphertext]
plain = [chr((char**key) % n) for char in ciphertext]
# Return the array of bytes as a string
return "".join(plain)

Expand Down
28 changes: 26 additions & 2 deletions homework01/vigenere.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,19 @@ def encrypt_vigenere(plaintext: str, keyword: str) -> str:
'LXFOPVEFRNHR'
"""
ciphertext = ""
# PUT YOUR CODE HERE
for i in range(len(plaintext)):
symbol = plaintext[i]
if symbol.isalpha():
if symbol.isupper():
shift = ord(keyword[i % len(keyword)]) - ord("A")
code_of_symbol = ord(symbol) - ord("A")
ciphertext += chr((code_of_symbol + shift) % 26 + ord("A"))
else:
shift = ord(keyword[i % len(keyword)]) - ord("a")
code_of_symbol = ord(symbol) - ord("a")
ciphertext += chr((code_of_symbol + shift) % 26 + ord("a"))
else:
ciphertext += symbol
return ciphertext


Expand All @@ -26,5 +38,17 @@ def decrypt_vigenere(ciphertext: str, keyword: str) -> str:
'ATTACKATDAWN'
"""
plaintext = ""
# PUT YOUR CODE HERE
for i in range(len(ciphertext)):
symbol = ciphertext[i]
if symbol.isalpha():
if symbol.isupper():
shift = ord(keyword[i % len(keyword)]) - ord("A")
code_of_symbol = 25 - ord(symbol) + ord("A")
plaintext += chr(25 - (code_of_symbol + shift) % 26 + ord("A"))
else:
shift = ord(keyword[i % len(keyword)]) - ord("a")
code_of_symbol = 25 - ord(symbol) + ord("a")
plaintext += chr(25 - (code_of_symbol + shift) % 26 + ord("a"))
else:
plaintext += symbol
return plaintext
95 changes: 78 additions & 17 deletions homework02/sudoku.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import pathlib
import random
import typing as tp

T = tp.TypeVar("T")


def read_sudoku(path: tp.Union[str, pathlib.Path]) -> tp.List[tp.List[str]]:
""" Прочитать Судоку из указанного файла """
"""Прочитать Судоку из указанного файла"""
path = pathlib.Path(path)
with path.open() as f:
puzzle = f.read()
Expand All @@ -19,7 +20,7 @@ def create_grid(puzzle: str) -> tp.List[tp.List[str]]:


def display(grid: tp.List[tp.List[str]]) -> None:
"""Вывод Судоку """
"""Вывод Судоку"""
width = 2
line = "+".join(["-" * (width * 3)] * 3)
for row in range(9):
Expand All @@ -42,7 +43,12 @@ def group(values: tp.List[T], n: int) -> tp.List[tp.List[T]]:
>>> group([1,2,3,4,5,6,7,8,9], 3)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
"""
pass
matrix = []
i = 0
for j in range(n, len(values) + 1, n):
matrix.append(values[i:j])
i = j
return matrix


def get_row(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -> tp.List[str]:
Expand All @@ -55,7 +61,7 @@ def get_row(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -> tp.List[str
>>> get_row([['1', '2', '3'], ['4', '5', '6'], ['.', '8', '9']], (2, 0))
['.', '8', '9']
"""
pass
return grid[pos[0]]


def get_col(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -> tp.List[str]:
Expand All @@ -68,7 +74,10 @@ def get_col(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -> tp.List[str
>>> get_col([['1', '2', '3'], ['4', '5', '6'], ['.', '8', '9']], (0, 2))
['3', '6', '9']
"""
pass
column = []
for i in range(len(grid)):
column.append(grid[i][pos[1]])
return column


def get_block(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -> tp.List[str]:
Expand All @@ -82,10 +91,16 @@ def get_block(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -> tp.List[s
>>> get_block(grid, (8, 8))
['2', '8', '.', '.', '.', '5', '.', '7', '9']
"""
pass
block = []
number_of_string = pos[0] // 3
number_of_column = pos[1] // 3
for i in range(number_of_string * 3, number_of_string * 3 + 3):
for j in range(number_of_column * 3, number_of_column * 3 + 3):
block.append(grid[i][j])
return block


def find_empty_positions(grid: tp.List[tp.List[str]]) -> tp.Optional[tp.Tuple[int, int]]:
def find_empty_positions(grid: tp.List[tp.List[str]]):
"""Найти первую свободную позицию в пазле

>>> find_empty_positions([['1', '2', '.'], ['4', '5', '6'], ['7', '8', '9']])
Expand All @@ -95,7 +110,14 @@ def find_empty_positions(grid: tp.List[tp.List[str]]) -> tp.Optional[tp.Tuple[in
>>> find_empty_positions([['1', '2', '3'], ['4', '5', '6'], ['.', '8', '9']])
(2, 0)
"""
pass
x = -1
for i in grid:
y = -1
x += 1
for j in i:
y += 1
if j == ".":
return x, y


def find_possible_values(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -> tp.Set[str]:
Expand All @@ -109,11 +131,18 @@ def find_possible_values(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -
>>> values == {'2', '5', '9'}
True
"""
pass


def solve(grid: tp.List[tp.List[str]]) -> tp.Optional[tp.List[tp.List[str]]]:
""" Решение пазла, заданного в grid """
numbers = set("123456789")
string = set(get_row(grid, pos))
column = set(get_col(grid, pos))
block = set(get_block(grid, pos))
numbers -= string
numbers -= column
numbers -= block
return numbers


def solve(grid: tp.List[tp.List[str]]):
"""Решение пазла, заданного в grid"""
""" Как решать Судоку?
1. Найти свободную позицию
2. Найти все возможные значения, которые могут находиться на этой позиции
Expand All @@ -125,13 +154,33 @@ def solve(grid: tp.List[tp.List[str]]) -> tp.Optional[tp.List[tp.List[str]]]:
>>> solve(grid)
[['5', '3', '4', '6', '7', '8', '9', '1', '2'], ['6', '7', '2', '1', '9', '5', '3', '4', '8'], ['1', '9', '8', '3', '4', '2', '5', '6', '7'], ['8', '5', '9', '7', '6', '1', '4', '2', '3'], ['4', '2', '6', '8', '5', '3', '7', '9', '1'], ['7', '1', '3', '9', '2', '4', '8', '5', '6'], ['9', '6', '1', '5', '3', '7', '2', '8', '4'], ['2', '8', '7', '4', '1', '9', '6', '3', '5'], ['3', '4', '5', '2', '8', '6', '1', '7', '9']]
"""
pass
pos = find_empty_positions(grid)
if pos is None:
return grid
else:
possible_values = find_possible_values(grid, pos)
for number in possible_values:
grid[pos[0]][pos[1]] = number
res = solve(grid)
if res:
return res
grid[pos[0]][pos[1]] = "."


def check_solution(solution: tp.List[tp.List[str]]) -> bool:
""" Если решение solution верно, то вернуть True, в противном случае False """
"""Если решение solution верно, то вернуть True, в противном случае False"""
# TODO: Add doctests with bad puzzles
pass
arr = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
for i in range(0, len(solution)):
for j in range(0, len(solution)):
pos = i, j
if not (
arr == sorted(get_row(solution, pos))
and arr == sorted(get_col(solution, pos))
and arr == sorted(get_block(solution, pos))
):
return False
return True


def generate_sudoku(N: int) -> tp.List[tp.List[str]]:
Expand All @@ -156,7 +205,14 @@ def generate_sudoku(N: int) -> tp.List[tp.List[str]]:
>>> check_solution(solution)
True
"""
pass
grid = [["." for _ in range(9)] for _ in range(9)]
if N > 81:
N = 81
dots = random.sample([i for i in range(81)], 81 - N)
solve(grid)
for elem in dots:
grid[elem // 9][elem % 9] = "."
return grid


if __name__ == "__main__":
Expand All @@ -168,3 +224,8 @@ def generate_sudoku(N: int) -> tp.List[tp.List[str]]:
print(f"Puzzle {fname} can't be solved")
else:
display(solution)
if check_solution(solution):
print("Solution is correct")
else:
print("Ooops")
display(generate_sudoku(1))
1 change: 1 addition & 0 deletions venv/Lib/site-packages/_black_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
version = "20.8b1"
1 change: 1 addition & 0 deletions venv/Lib/site-packages/appdirs-1.4.4.dist-info/INSTALLER
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pip
23 changes: 23 additions & 0 deletions venv/Lib/site-packages/appdirs-1.4.4.dist-info/LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# This is the MIT license

Copyright (c) 2010 ActiveState Software Inc.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Loading