Skip to content
Open

HW 2 #61

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
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"python.formatting.provider": "yapf"
}
21 changes: 21 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Run program (.py)",
"command": "python3",
"args": [
"${file}"
],
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"clear": true
}
}
]
}
2 changes: 2 additions & 0 deletions hw1/task_1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
if __name__ == "__main__":
print(sum(map(float, input().split())))
34 changes: 34 additions & 0 deletions hw1/task_2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
def input_data():
print('Enter main text:')
text = input()
print(
'Enter substitution rules (e. g. A->B, C->D, ...), enter "end" to stop:'
)
data = input()
substitution_rules = {}
while data != 'end':
pair = data.split('->')
substitution_rules[pair[0]] = pair[1]
data = input()
return text, substitution_rules


def print_data(text, substitution_rules):
print('Input data:')
print(text)
for i in substitution_rules.keys():
print(i, substitution_rules[i])


def process_data(text, substitution_rules):
for i in substitution_rules:
text = text.replace(i, substitution_rules[i])
return text


if __name__ == "__main__":
# text, substitution_rules = input_data()
text = 'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG'
substitution_rules = {'A': '4', 'I': '1', 'E': '3'}
text = process_data(text, substitution_rules)
print(text)
8 changes: 8 additions & 0 deletions hw1/task_3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
def f1(n):
return abs(int(float(n)))


if __name__ == "__main__":
# text = '0.23 0 -12 5 -7.11 2'
text = input()
print(*map(f1, text.split()))
8 changes: 8 additions & 0 deletions hw1/task_4.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
def f1(n):
return float(n)**2


if __name__ == "__main__":
# text = '2 -5 -12 0.33 7 2'
text = input()
print(sum(map(f1, text.split())))
13 changes: 13 additions & 0 deletions hw1/task_5.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
def cesar_scheme(text, num):
a_num = ord('a')
alph_num = ord('z') - a_num + 1
s = ''
for i in text:
i_num = ord(i)
s += chr(((i_num - a_num + num) % alph_num) + a_num)
return s


if __name__ == "__main__":
text = input()
print(cesar_scheme(text, 7))
68 changes: 68 additions & 0 deletions hw2/decoder.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import math
import sys


def index_to_bytes(value, bits):
n = bits // 8
if bits % 8 != 0:
n += 1
return value.to_bytes(n, 'little')


def num_of_bytes_to_read(dict_len):
bits = math.ceil(
math.log2(dict_len)
) # кол-во бит для представления числа len(dictionary) в binary формате (чтобы уместилось)
bytes = bits // 8 # кол-во байт (получаем из кол-ва бит)
if bits % 8 != 0:
bytes += 1
return bytes


def bytes_to_index(bytes_str):
index = int.from_bytes(bytes_str,
'little') # переводим байт/байты в индекс
return index


if __name__ == '__main__':
if len(sys.argv) == 1 or len(sys.argv) >= 4:
print('Usage: python', sys.argv[0], 'input_file')
print(
'На входе должно быть от 1 или 2 аргумента (не считая сам исполняемый файл .py)!'
)
exit(-1)

with open(sys.argv[1], 'rb') as file:
data = file.read()
dictionary = {i: (i, ) for i in range(256)}
sequence = list()

outpath = sys.argv[2] if len(sys.argv) == 3 else sys.argv[1] + '.dec'
with open(outpath, 'wb') as file:
i = 0
while i < len(data):
n = len(dictionary) if i != 1 else len(
dictionary) + 1 # чтобы считать два байта
bits = math.ceil(math.log2(n))
Bytes = math.ceil(
bits / 8
) # кол-во байт для считывания (в первый раз - 1, затем - 2 и т.д.)
ind = bytes_to_index(
data[i:i +
Bytes]) # индекс соответствующей байт. последовательности
if ind == len(dictionary):
temp = []
temp.append(sequence[0])
dec_out = sequence + temp
sequence.append(dec_out[0])
else:
dec_out = list(dictionary[ind])
sequence.append(dec_out[0])
file.write(bytes(dec_out))
if i == 0:
i += Bytes
continue
i += Bytes
dictionary[len(dictionary)] = tuple(sequence)
sequence = dec_out
61 changes: 61 additions & 0 deletions hw2/decoder_wrong.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import math
import sys


def index_to_bytes(value, bits):
n = bits // 8
if bits % 8 != 0:
n += 1
return value.to_bytes(n, 'little')


def num_of_bytes_to_read(dict_len):
bits = math.ceil(
math.log2(dict_len)
) # кол-во бит для представления числа len(dictionary) в binary формате (чтобы уместилось)
bytes = bits // 8 # кол-во байт (получаем из кол-ва бит)
if bits % 8 != 0:
bytes += 1
return bytes


def bytes_to_index(bytes_str):
index = int.from_bytes(bytes_str,
'little') # переводим байт/байты в индекс
return index


if __name__ == '__main__':
if len(sys.argv) == 1 or len(sys.argv) >= 4:
print('Usage: python', sys.argv[0], 'input_file')
print(
'На входе должно быть от 1 или 2 аргумента (не считая сам исполняемый файл .py)!'
)
exit(-1)

with open(sys.argv[1], 'rb') as file:
data = file.read()
dictionary = {i: (i, ) for i in range(256)}
sequence = list()
nseq = list()

outpath = sys.argv[2] if len(sys.argv) == 3 else sys.argv[1] + '.dec'
with open(outpath, 'wb') as file:
i = 0
while i < len(data):
n = len(dictionary)
bits = math.ceil(math.log2(n))
Bytes = math.ceil(
bits / 8
) # кол-во байт для считывания (в первый раз - 1, затем - 2 и т.д.)
ind = bytes_to_index(
data[i:i +
Bytes]) # индекс соответствующей байт. последовательности
if ind == len(dictionary):
nseq = sequence + sequence[-1:]
else:
nseq = sequence + list(dictionary[ind])
file.write(bytes(nseq))
dictionary[len(dictionary)] = tuple(sequence + nseq[-1:])
i += Bytes
seq = nseq.copy()
44 changes: 44 additions & 0 deletions hw2/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import math
import sys


def index_to_bytes(value, bits):
n = bits // 8
if bits % 8 != 0:
n += 1
return value.to_bytes(n, 'little')


if __name__ == '__main__':
if len(sys.argv) == 1:
print('Usage: python', sys.argv[0], 'input_file')
exit(-1)
with open(sys.argv[1], 'rb') as file:
data = file.read()
dictionary = {(i,): i for i in range(256)}
sequence = list()

outpath = sys.argv[2] if len(sys.argv) == 3 else sys.argv[1] + '.lzw'
with open(outpath, 'wb') as file:
for sym in data:
sequence.append(sym)
key = tuple(sequence)
if key in dictionary:
continue

n = math.ceil(
math.log2(len(dictionary))) # кол-во бит для представления числа len(dictionary) в binary формате
index_value = dictionary[key[:-1]]
enc_value = index_to_bytes(index_value, n)
file.write(enc_value)

value = len(dictionary)
dictionary[key] = value
# print(value, '->', key)
sequence = sequence[-1:]

n = math.ceil(
math.log2(len(dictionary))) # кол-во бит для представления числа len(dictionary) в 2-ом формате
index_value = dictionary[tuple(sequence)]
enc_value = index_to_bytes(index_value, n)
file.write(enc_value)
Binary file added hw2/main.py.lzw
Binary file not shown.
44 changes: 44 additions & 0 deletions hw2/main.py.lzw.dec
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import math
import sys


def index_to_bytes(value, bits):
n = bits // 8
if bits % 8 != 0:
n += 1
return value.to_bytes(n, 'little')


if __name__ == '__main__':
if len(sys.argv) == 1:
print('Usage: python', sys.argv[0], 'input_file')
exit(-1)
with open(sys.argv[1], 'rb') as file:
data = file.read()
dictionary = {(i,): i for i in range(256)}
sequence = list()

outpath = sys.argv[2] if len(sys.argv) == 3 else sys.argv[1] + '.lzw'
with open(outpath, 'wb') as file:
for sym in data:
sequence.append(sym)
key = tuple(sequence)
if key in dictionary:
continue

n = math.ceil(
math.log2(len(dictionary))) # кол-во бит для представления числа len(dictionary) в binary формате
index_value = dictionary[key[:-1]]
enc_value = index_to_bytes(index_value, n)
file.write(enc_value)

value = len(dictionary)
dictionary[key] = value
# print(value, '->', key)
sequence = sequence[-1:]

n = math.ceil(
math.log2(len(dictionary))) # кол-во бит для представления числа len(dictionary) в 2-ом формате
index_value = dictionary[tuple(sequence)]
enc_value = index_to_bytes(index_value, n)
file.write(enc_value)
1 change: 1 addition & 0 deletions hw2/test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
banana_bandana
1 change: 1 addition & 0 deletions hw2/test1.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ababababababababa
Binary file added hw2/test1.txt.lzw
Binary file not shown.