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
43 changes: 43 additions & 0 deletions Task2_encode_decode.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# problem1
# 1st version
def en_code(word):
bin_word = []
for item in word:
bin_word.append("{:08b}".format(ord(item)))
result = "".join(bin_word)
return result


# 2nd version
def en_code1(word):
return "".join("{:08b}".format(ord(item)) for item in word)

# problem 2
# 1st version


def de_code_input(bin_type):
if len(bin_type) % 8 != 0:
return False
for item in bin_type:
if item not in ("0", "1"):
return False
return True


def de_code(bin_type):
stack_num = []
word = []
new_bin_type = [item for item in bin_type]
while len(new_bin_type) > 0:
while len(stack_num) < 8:
stack_num.append(new_bin_type.pop(0))
word.append(chr(int("".join(stack_num), 2)))
stack_num.clear()
return "".join(word)


# 2nd version
def de_code2(bin_type):
return "".join([chr(int(item1, 2))for item1 in [bin_type[item:item+8] for item in range(0, len(bin_type), 8)]])

19 changes: 19 additions & 0 deletions result.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from Task2_encode_decode import *


def rep_dec_enc():
print("Choose what you want to do:Encode or Decode? ")
answer = input("Type 1 or 2: ")
if answer == "1":
word = input("Please input a string: ")
print(f"The answer is: {en_code1(word)}") # or en_code
else:
while True:
bin_type = input("Please input a binary code(it can contain only 0 or 1): ")
if de_code_input(bin_type) == True:
break
print(f"The answer is: {de_code2(bin_type)}") # or de_code


if __name__ == '__main__':
rep_dec_enc()