Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

homework01 поток 1.2 Новицкая Е.М. #103

Closed
wants to merge 12 commits into from
33 changes: 33 additions & 0 deletions homework01/01допзадание.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
def encrypt_poly_shift(plaintext: str, odd_shift: int, even_shift: int) -> str:
alphabet = "абвгдежзийклмнопрстуфхцчшщъыьэюя"
alphabet_length = len(alphabet)

encrypted_text = []

for index, char in enumerate(plaintext):
position = index + 1

if char.lower() in alphabet:
shift = odd_shift if position % 2 != 0 else even_shift

original_index = alphabet.index(char.lower())

new_index = (original_index + shift) % alphabet_length

encrypted_char = alphabet[new_index]

if char.isupper():
encrypted_text.append(encrypted_char.upper())
else:
encrypted_text.append(encrypted_char)
else:
encrypted_text.append(char)

return "".join(encrypted_text)


plaintext = input()
odd_shift = int(input())
even_shift = int(input())
encrypted = encrypt_poly_shift(plaintext, odd_shift, even_shift)
print(encrypted)
29 changes: 26 additions & 3 deletions homework01/caesar.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
def encrypt_caesar(plaintext: str, shift: int = 3) -> str:
"""
Encrypts plaintext using a Caesar cipher.

>>> encrypt_caesar("PYTHON")
'SBWKRQ'
>>> encrypt_caesar("python")
Expand All @@ -11,13 +12,22 @@ def encrypt_caesar(plaintext: str, shift: int = 3) -> str:
''
"""
ciphertext = ""
# PUT YOUR CODE HERE
for S in plaintext:
if "A" <= S <= "Z":
new_s = chr((ord(S) - ord("A") + shift) % 26 + ord("A"))
ciphertext += new_s
elif "a" <= S <= "z":
new_s = chr((ord(S) - ord("a") + shift) % 26 + ord("a"))
ciphertext += new_s
else:
ciphertext += S
return ciphertext


def decrypt_caesar(ciphertext: str, shift: int = 3) -> str:
"""
Decrypts a ciphertext using a Caesar cipher.

>>> decrypt_caesar("SBWKRQ")
'PYTHON'
>>> decrypt_caesar("sbwkrq")
Expand All @@ -28,5 +38,18 @@ def decrypt_caesar(ciphertext: str, shift: int = 3) -> str:
''
"""
plaintext = ""
# PUT YOUR CODE HERE
return plaintext
for S in ciphertext:
if "A" <= S <= "Z":
new_s = chr((ord(S) - ord("A") - shift) % 26 + ord("A"))
plaintext += new_s
elif "a" <= S <= "z":
new_s = chr((ord(S) - ord("a") - shift) % 26 + ord("a"))
plaintext += new_s
else:
plaintext += S
return plaintext


if __name__ == "__main__":
print(encrypt_caesar(input()))
print(decrypt_caesar(input()))
41 changes: 28 additions & 13 deletions homework01/rsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,17 @@ def is_prime(n: int) -> bool:
>>> is_prime(8)
False
"""
# PUT YOUR CODE HERE
pass
count = 0
for i in range(2, n - 1):
if abs(n) % i == 0:
count += 1
break
if n <= 1:
count += 1
if count == 0:
return True
else:
return False


def gcd(a: int, b: int) -> int:
Expand All @@ -24,8 +33,11 @@ def gcd(a: int, b: int) -> int:
>>> gcd(3, 7)
1
"""
# PUT YOUR CODE HERE
pass
m = 0
for i in range(1, max(a, b) + 1):
if a % i == 0 and b % i == 0 and i > m:
m = i
return m


def multiplicative_inverse(e: int, phi: int) -> int:
Expand All @@ -35,21 +47,24 @@ def multiplicative_inverse(e: int, phi: int) -> int:
>>> multiplicative_inverse(7, 40)
23
"""
# PUT YOUR CODE HERE
pass
d = 1
if (e == 1) or (phi == 1):
d = 0
else:
while (d * e) % phi != 1:
d += 1

return d


def generate_keypair(p: int, q: int) -> tp.Tuple[tp.Tuple[int, int], tp.Tuple[int, int]]:
if not (is_prime(p) and is_prime(q)):
raise ValueError("Both numbers must be prime.")
elif p == q:
raise ValueError("p and q cannot be equal")
n = p * q

# n = pq
# PUT YOUR CODE HERE

# 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 Down Expand Up @@ -82,7 +97,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 All @@ -100,4 +115,4 @@ def decrypt(pk: tp.Tuple[int, int], ciphertext: tp.List[int]) -> str:
print("".join(map(lambda x: str(x), encrypted_msg)))
print("Decrypting message with public key ", public, " . . .")
print("Your message is:")
print(decrypt(public, encrypted_msg))
print(decrypt(public, encrypted_msg))
63 changes: 60 additions & 3 deletions homework01/vigenere.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,37 @@ def encrypt_vigenere(plaintext: str, keyword: str) -> str:
>>> encrypt_vigenere("ATTACKATDAWN", "LEMON")
'LXFOPVEFRNHR'
"""

if len(plaintext) > len(keyword):
diff = len(plaintext) - len(keyword)
for i in range(diff):
keyword += keyword[i]
nums = []
ciphertext = ""
# PUT YOUR CODE HERE

for i in range(len(keyword)):
if keyword[i].isalpha():
if keyword[i].islower():
nums.append((ord(keyword[i]) - ord("a")) % 26)
else:
nums.append((ord(keyword[i]) - ord("A")) % 26)
else:
nums.append(0)

for i in range(len(nums)):
if plaintext[i].isalpha():
if plaintext[i].islower():
if ord(plaintext[i]) + nums[i] <= ord("z"):
ciphertext += chr(ord(plaintext[i]) + nums[i])
else:
ciphertext += chr(ord(plaintext[i]) + nums[i] - 26)
else:
if ord(plaintext[i]) + nums[i] <= ord("Z"):
ciphertext += chr(ord(plaintext[i]) + nums[i])
else:
ciphertext += chr(ord(plaintext[i]) + nums[i] - 26)
else:
ciphertext += plaintext[i]
return ciphertext


Expand All @@ -23,6 +52,34 @@ def decrypt_vigenere(ciphertext: str, keyword: str) -> str:
>>> decrypt_vigenere("LXFOPVEFRNHR", "LEMON")
'ATTACKATDAWN'
"""

if len(ciphertext) > len(keyword):
diff = len(ciphertext) - len(keyword)
for i in range(diff):
keyword += keyword[i]
nums = []
plaintext = ""
# PUT YOUR CODE HERE
return plaintext
for i in range(len(ciphertext)):
if keyword[i].isalpha():
if keyword[i].islower():
nums.append((ord(keyword[i]) - ord("a")) % 26)
else:
nums.append((ord(keyword[i]) - ord("A")) % 26)
else:
nums.append(0)

for i in range(len(nums)):
if ciphertext[i].isalpha():
if ciphertext[i].islower():
if ord(ciphertext[i]) - nums[i] >= ord("a"):
plaintext += chr(ord(ciphertext[i]) - nums[i])
else:
plaintext += chr(ord(ciphertext[i]) - nums[i] + 26)
else:
if ord(ciphertext[i]) - nums[i] >= ord("A"):
plaintext += chr(ord(ciphertext[i]) - nums[i])
else:
plaintext += chr(ord(ciphertext[i]) - nums[i] + 26)
else:
plaintext += ciphertext[i]
return plaintext
16 changes: 6 additions & 10 deletions homework02/sudoku.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@


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,15 +19,11 @@ 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):
print(
"".join(
grid[row][col].center(width) + ("|" if str(col) in "25" else "") for col in range(9)
)
)
print("".join(grid[row][col].center(width) + ("|" if str(col) in "25" else "") for col in range(9)))
if str(row) in "25":
print(line)
print()
Expand Down Expand Up @@ -107,7 +103,7 @@ def find_possible_values(grid: tp.List[tp.List[str]], pos: tp.Tuple[int, int]) -


def solve(grid: tp.List[tp.List[str]]) -> tp.Optional[tp.List[tp.List[str]]]:
""" Решение пазла, заданного в grid """
"""Решение пазла, заданного в grid"""
""" Как решать Судоку?
1. Найти свободную позицию
2. Найти все возможные значения, которые могут находиться на этой позиции
Expand All @@ -122,7 +118,7 @@ def solve(grid: tp.List[tp.List[str]]) -> tp.Optional[tp.List[tp.List[str]]]:


def check_solution(solution: tp.List[tp.List[str]]) -> bool:
""" Если решение solution верно, то вернуть True, в противном случае False """
"""Если решение solution верно, то вернуть True, в противном случае False"""
# TODO: Add doctests with bad puzzles
pass

Expand Down Expand Up @@ -159,4 +155,4 @@ def generate_sudoku(N: int) -> tp.List[tp.List[str]]:
if not solution:
print(f"Puzzle {fname} can't be solved")
else:
display(solution)
display(solution)
2 changes: 1 addition & 1 deletion homework02/test_sudoku.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,4 +239,4 @@ def test_generate_sudoku(self):
self.assertEqual(expected_unknown, actual_unknown)
solution = sudoku.solve(grid)
solved = sudoku.check_solution(solution)
self.assertTrue(solved)
self.assertTrue(solved)
Loading
Loading