Added Lab2/Lab3 IS

This commit is contained in:
sherlock 2025-08-12 09:43:39 +05:30
parent 011d5aded1
commit 0755dd4b76
6 changed files with 109 additions and 140 deletions

View file

@ -1,18 +1,14 @@
def generate_playfair_matrix(key):
key = ''.join(sorted(set(key.upper()), key=key.upper().index))
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
matrix = []
for char in key:
if char not in matrix and char != 'J':
matrix.append(char)
for char in alphabet:
if char not in matrix and char != 'J':
matrix.append(char)
playfair_matrix = [matrix[i:i+5] for i in range(0, len(matrix), 5)]
return playfair_matrix
alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ" # J omitted
unique = []
for ch in key:
if ch != 'J' and ch not in unique:
unique.append(ch)
for ch in alphabet:
if ch not in unique:
unique.append(ch)
return [unique[i:i+5] for i in range(0, 25, 5)]
def find_pos(matrix, char):
for row_idx, row in enumerate(matrix):
@ -22,16 +18,14 @@ def find_pos(matrix, char):
return None
def prepare_text(text):
text = ''.join(filter(str.isalpha, text.upper()))
text = text.replace('J', 'I')
pairs = []
i = 0
text = ''.join(ch for ch in text.upper() if ch.isalpha()).replace('J', 'I')
pairs, i = [], 0
while i < len(text):
if i + 1 < len(text) and text[i] != text[i+1]:
pairs.append(text[i:i+2])
if i + 1 < len(text) and text[i] != text[i + 1]:
pairs.append(text[i:i + 2])
i += 2
else:
pairs.append(text[i]+'X')
pairs.append(text[i] + 'X')
i += 1
return pairs