This commit is contained in:
José Henrique 2023-08-22 13:29:32 -03:00
commit a3306596e1
2 changed files with 136 additions and 0 deletions

60
trabalho1/afreq.py Normal file
View File

@ -0,0 +1,60 @@
frequencias = {
'A': 14.63,
'B': 1.04,
'C': 3.88,
'D': 4.99,
'E': 12.57,
'F': 1.02,
'G': 1.30,
'H': 1.28,
'I': 6.18,
'J': 0.40,
'K': 0.02,
'L': 2.78,
'M': 4.74,
'N': 5.05,
'O': 10.73,
'P': 2.52,
'Q': 1.20,
'R': 6.53,
'S': 7.81,
'T': 4.34,
'U': 4.63,
'V': 1.67,
'W': 0.01,
'X': 0.21,
'Y': 0.01,
'Z': 0.47
}
def afreq(string):
# determinar a frequencia de cada caractere na string
# comparar com a frequencia de cada caractere na lingua portuguesa
# calcular a diferenca entre as frequencias
str_freq = {}
for c in string:
if not c.isalnum():
continue
if c in str_freq:
str_freq[c] += 1
else:
str_freq[c] = 1
for c in str_freq:
if not c.isalnum():
continue
str_freq[c] /= len(string)
freq_sorted = dict(sorted(str_freq.items(), key=lambda item: item[1]))
possiveis_chaves = []
for c in frequencias:
for k in freq_sorted:
if abs(frequencias[c] - freq_sorted[k]) < 0.5:
possiveis_chaves.append(ord(k) - ord(c))
return possiveis_chaves

76
trabalho1/cesar.py Normal file
View File

@ -0,0 +1,76 @@
import sys
if len(sys.argv) != 4:
print("Usage: python3 cesar.py -c/-d [key] [string]")
sys.exit(1)
encrypt = True
if sys.argv[1] == "-d":
encrypt = False
key = int(sys.argv[2])
string = sys.argv[3]
if not encrypt:
key *= -1
special_letters = {
"ã": "a",
"á": "a",
"à": "a",
"é": "e",
"ê": "e",
"í": "i",
"ó": "o",
"õ": "o",
"ô": "o",
"ú": "u",
"ç": "c"
}
special_chars = {
" ": " ",
".": ".",
",": ",",
";": ";",
":": ":",
"!": "!",
"?": "?",
"(": "(",
")": ")"
}
def cesar(string, key):
new_string = ""
for letter in string:
if letter in special_chars:
new_string += special_chars[letter]
continue
if letter in special_letters:
letter = special_letters[letter]
new_letter = ord(letter) + key
# [A-Z, a-z, 0-9]
if ord('0') <= ord(letter) <= ord('9'):
if new_letter > ord('9'):
new_letter += 7 # 9 + 1 = A
elif new_letter < ord('0'):
new_letter += 75 # 0 - 1 = z
elif letter.isupper():
if new_letter > ord('Z'):
new_letter += 6 # Z + 1 = a
elif new_letter < ord('A'):
new_letter -= 7 # A - 1 = 9
else:
if new_letter > ord('z'):
new_letter -= 75 # z + 1 = 0
elif new_letter < ord('a'):
new_letter -= 6 # a - 1 = Z
new_string += chr(new_letter)
return new_string
print(cesar(string, key))