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
38 changes: 38 additions & 0 deletions Lesson_1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""
Задание 1.
Докажите, что словари обрабатываются быстрее, чем списки.
Реализуйте две функции, в первой нужно заполнить элементами список, во второй-словарь
Сделайте замеры времени выполнения каждой из функций
Подсказка: для замеров воспользуйтесь модулем time (см. примеры урока 1)
Примечание: eсли вы уже знаете, что такое декоратор и как его реализовать,
то реализуйте ф-цию-декоратор и пусть она считает время
И примените ее к двум своим функциям.
"""

import time
import random as rnd


def time_of_function(function):
def wrapped(*args):
start_time = time.perf_counter()
res = function(*args)
print(f'Execution time for {function} is {time.perf_counter() - start_time} sec')
return res
return wrapped

@time_of_function
def fill_list(number):
reslist = []
reslist = [rnd.randint(1, 5) for i in range(1, number) ]

fill_list(10000000)

@time_of_function
def fill_dict(number):
resdict = {}
for i in range(1, number):
val = rnd.randint(1, 5)
resdict.update(i = val)

fill_dict(10000000)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нет аналитики
минус балл

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я еще дописал функцию (fill_dict_1 ) заполняющую словарь через генератор и получил время все равно хуже, чем заполнение списка. Я так понимаю, что работа со списком реализована оптимальнее.

Execution time for <function fill_list at 0x000001F2723E28B0> is 7.2645058 sec
Execution time for <function fill_dict at 0x000001F2723E29D0> is 8.423135600000002 sec
Execution time for <function fill_dict_1 at 0x000001F2723E2B80> is 8.650617299999999 sec

82 changes: 82 additions & 0 deletions Lesson_2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
"""
Задание 2.
Ваша программа должна запрашивать пароль
Для этого пароля вам нужно получить хеш, используя функцию sha256
Для генерации хеша обязательно нужно использовать криптографическую соль
Обязательно выведите созданный хеш

Далее программа должна запросить пароль повторно
Вам нужно проверить, совпадает ли пароль с исходным
Для проверки необходимо сравнить хеши паролей

ПРИМЕР:
Введите пароль: 123
В базе данных хранится строка: 555a3581d37993843efd4eba1921f1dcaeeafeb855965535d77c55782349444b
Введите пароль еще раз для проверки: 123
Вы ввели правильный пароль
"""

import os
from hashlib import pbkdf2_hmac
from binascii import hexlify

cwd = os.getcwd()
longin, passwd = '', ''

def check_login(p_login):
with(open(cwd + '\\' + 'Lesson_2.txt')) as f:
for data in f.readlines():
login, _ = data.strip().split(' ')
if p_login == login:
return True
else:
continue
return False

def create_login(p_login):
passwd = input('Plase provide password: ')
obj = pbkdf2_hmac(hash_name='sha256',
password=bytes(passwd, 'utf-8'),
salt=bytes(login, 'utf-8'),
iterations=100000)
passwd = hexlify(obj)
with(open(cwd + '\\' + 'Lesson_2.txt', 'a')) as f:
f.write(login + ' ' + str(passwd) + '\n')

def authent(p_login):
p_passwd = input('Plase provide password: ')
obj = pbkdf2_hmac(hash_name='sha256', password=bytes(p_passwd, 'utf-8'), salt=bytes(p_login, 'utf-8'), iterations=100000)
p_passwd = hexlify(obj)
with(open(cwd + '\\' + 'Lesson_2.txt')) as f:
for data in f.readlines():
login, passwd = data.strip().split(' ')
if p_login == login and str(p_passwd) == passwd:
return True

while True:
login = input('Please provide your login: ').lstrip().rstrip()
if not check_login(login):
answer = input('You do not have login. Do you want to create it?: (y / n) ').lstrip().rstrip()
if answer == 'y':
login = input('Please provide a new login: ').lstrip().rstrip()
if check_login(login):
print(f'Login {login} is already present, please retype')
else:
create_login(login)
print(f'Your Login {login} has been created successfully')
elif answer == 'n':
print('Bye')
break
else:
if authent(login):
print('You are successfully authenticated. Welcome!')
break
else:
print('Provided password is wrong')
answer = input('For new attempts press "y" for exit "n") ').lstrip().rstrip()
if answer == 'y':
continue
else:
break


Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

хорошо

4 changes: 4 additions & 0 deletions Lesson_2.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
alexak b'1b147d7c686b0da33a61c20f8bf7dcae962eccf505dcae07e64b059af1497661'
bob b'3e38099ec76158fc4dcbd75998ba506285d8d558b3fca74d89eb03acfb67f621'
john b'27a42d3a0babc123113a325b5886e6aaca3d6ed4f3bedbca05b2ab19941dac55'
al b'06550291689284398a3885339648bd30b506f4708141d9d26bf51051c5d69d3c'
31 changes: 31 additions & 0 deletions Lesson_3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""
Задание 3.
Определить количество различных подстрок с использованием хеш-функции.
Дана строка S длиной N, состоящая только из строчных латинских букв.

Подсказка: примените хеши и множества

рара:

рар
ра
ар
ара
р
а
"""
import hashlib

inp_str = input('Please provide any string contains only English letters:')
s = set()
n = len(inp_str)

for i in range(0, n+1):
for j in range(0, n+1):
h_inp_str = hashlib.sha256(bytes(inp_str, 'utf-8')).hexdigest()
h_substr = hashlib.sha256(bytes(inp_str[i : j], 'utf-8')).hexdigest()
if h_substr == h_inp_str or inp_str[i:j] == '':
continue
else:
s.add(inp_str[i:j])
print(s)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

хорошо

74 changes: 74 additions & 0 deletions Lesson_4.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
"""
Задание 4.
Реализуйте скрипт "Кэширование веб-страниц"

Функция должна принимать url-адрес и проверять
есть ли в кэше соответствующая страница, если нет, то вносит ее в кэш

Подсказка: задачу решите обязательно с применением 'соленого' хеширования
Можете условжнить задачу, реализовав ее через ООП
"""

import os
from hashlib import pbkdf2_hmac
from binascii import hexlify

cwd = os.getcwd()
salt = 'This is salt for URLs'

def print_url():
result = ''
with(open(cwd + '\\' + 'Lesson_4.txt')) as f:
for data in f.readlines():
url, _ = data.strip().split(' ')
result += url + '\n'
return result

def check_url(p_url):
with(open(cwd + '\\' + 'Lesson_4.txt')) as f:
for data in f.readlines():
if data == '' or data == '/n':
return False
else:
url, _ = data.strip().split(' ')
if p_url == url:
return True
else:
continue
return False

def cach_url(p_url):
obj = pbkdf2_hmac(hash_name='sha256',
password=bytes(p_url, 'utf-8'),
salt=bytes(salt, 'utf-8'),
iterations=100000)
hash_url = hexlify(obj)
with(open(cwd + '\\' + 'Lesson_4.txt', 'a')) as f:
f.write(p_url + ' ' + str(hash_url) + '\n')


while True:
print(f'These URLs have been cashed\n{print_url()}')
inp_str = input('Plase provide new URL or press "q" for exit:').lstrip().rstrip()
if inp_str.lower() == 'q':
break
if not check_url(inp_str):
print(f'There is no cash for URL {inp_str}')
answer = input('Create (y/n): ').lstrip().rstrip()
if answer.lower() == 'y':
cach_url(inp_str)
print(f'URL {inp_str} has been created')
answer = input('Continue? (y/n): ').lstrip().rstrip()
if answer.lower() == 'y':
continue
else:
break
else:
break
else:
print(f'Cash for {inp_str} is already present')
answer = input('Continue? (y/n): ').lstrip().rstrip()
if answer.lower() == 'y':
continue
else:
break
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

выполнено

6 changes: 6 additions & 0 deletions Lesson_4.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
www b'9af367ded7e7eba3652911d03c52ed92b7503df0c511e78aebec71e3ed9d4792'
www.ya b'972887ffeb1ceb91b2e1ce38d870aae9af293487d96f434b4f977cd847f37978'
www.ya.ru b'68738f2ce74bbea1bce9ae672ecc9399b4821e5faab9b4f31a5e20f710145e81'
www.yandex.ru b'29355e8eb35b32be2b3ccb5e1a857dd7ed523df68e71daf3e44a9cddf578377b'
www.rs b'07f6a1d2d8a399f7fbe1eb182c6ae3e7ceabf2f3e485afff88c0e8aa4612c55d'
www.ps.ru b'62a2b3be29af4a22510bbbd55d155f03ee7d8c25f45a31d52eba6a4ebc32265b'