-
Notifications
You must be signed in to change notification settings - Fork 77
It's addition files for Lesson 1 #598
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kalenikai
wants to merge
1
commit into
DmitryChitalov:master
Choose a base branch
from
kalenikai:Lesson_1_add
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| """ | ||
| Задание 1. | ||
|
|
||
| Для каждой из трех задач выполнить следующее: | ||
|
|
||
| 1) для каждой инструкции рядом в комментарии определите сложность этой инструкции | ||
| 2) определите сложность алгоритма в целом | ||
|
|
||
| укажите сложность непосредственно в этом файле | ||
| точки, где нужно поработать вам, отмечены знаком '!!!' | ||
|
|
||
| Примечание: | ||
| Если у вас возникают сложности, постарайтесь подумать как можно решить задачу, | ||
| а не писать "мы это не проходили)". | ||
| Алгоритмизатор должен развивать мышление, а это прежде всего практика. | ||
| А без столкновения со сложностями его не развить. | ||
| """ | ||
|
|
||
| import random | ||
|
|
||
|
|
||
| ############################################################################################# | ||
| def check_1(lst_obj): | ||
| """Функция должна создать множество из списка. | ||
|
|
||
| Алгоритм 3: | ||
| Создать множество из списка | ||
|
|
||
| Сложность: !!!. | ||
| """ | ||
| lst_to_set = set(lst_obj) # !!! | ||
| return lst_to_set | ||
|
|
||
|
|
||
| ############################################################################################# | ||
| def check_2(lst_obj): | ||
| """Функция должная вернуть True, если все элементы списка различаются. | ||
|
|
||
| Алгоритм 1: | ||
| Проходимся по списку и для каждого элемента проверяем, | ||
| что такой элемент отстутствует | ||
| в оставшихся справа элементах | ||
|
|
||
| Сложность: !!!. | ||
| """ | ||
| for j in range(len(lst_obj)): # !!! | ||
| if lst_obj[j] in lst_obj[j+1:]: # !!! | ||
| return False # !!! | ||
| return True # !!! | ||
|
|
||
|
|
||
| ############################################################################################# | ||
| def check_3(lst_obj): | ||
| """Функция должная вернуть True, если все элементы списка различаются. | ||
|
|
||
| Алгоритм 2: | ||
| Вначале выполним для списка сортировку, далее, сравниваем элементы попарно | ||
| Если присутствуют дубли, они будут находиться рядом. | ||
|
|
||
| Сложность: !!! | ||
| """ | ||
| lst_copy = list(lst_obj) # !!! | ||
| lst_copy.sort() # !!! | ||
| for i in range(len(lst_obj) - 1): # !!! | ||
| if lst_copy[i] == lst_copy[i+1]: # !!! | ||
| return False # !!! | ||
| return True # !!! | ||
|
|
||
| ############################################################################################# | ||
|
|
||
|
|
||
| for j in (50, 500, 1000, 5000, 1000): | ||
| # Из 100000 чисел возьмем 'j' случайно выбранных | ||
| # Всего 10 тыс. чисел | ||
| lst = random.sample(range(-100000, 100000), j) | ||
|
|
||
| print(check_1(lst)) | ||
| print(check_2(lst)) | ||
| print(check_3(lst)) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| # Задание 2. | ||
| # Реализуйте два алгоритма. | ||
| # Первый, в виде функции, должен обеспечивать поиск минимального значения для списка. | ||
| # В основе алгоритма должно быть сравнение каждого числа со всеми другими элементами списка. | ||
| # Сложность такого алгоритма: O(n^2) - квадратичная. | ||
| # Второй, в виде функции, должен обеспечивать поиск минимального значения для списка. | ||
| # Сложность такого алгоритма: O(n) - линейная. | ||
|
|
||
| # 1 | ||
| import random as rnd | ||
| int_list = [rnd.randint(0, 1000) for p in range(0, 20)] | ||
| print(int_list) | ||
| result = int_list[0] | ||
| for el in int_list: | ||
| if result > el: | ||
| result = el | ||
| print(result) | ||
|
|
||
| # 2 | ||
| import random as rnd | ||
| int_list = [rnd.randint(0, 1000) for p in range(0, 20)] | ||
| print(int_list) | ||
| print(sorted(int_list)[0]) | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. нарушение пеп по импортам |
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| """ | ||
| Сама задача: | ||
| Имеется хранилище с информацией о компаниях: название и годовая прибыль. | ||
| Для реализации хранилища можно применить любой подход, | ||
| который вы придумаете, например, реализовать словарь. | ||
| Реализуйте поиск трех компаний с наибольшей годовой прибылью. | ||
| Выведите результат. | ||
| """ | ||
|
|
||
| # 1 | ||
| dict_profit = {} | ||
| dict_company = {'Yarl' : 3460, 'Quark' : 4000, 'Cityland' : 2690, 'Ion': 1000, 'Drink': 8000, 'Drank' : 34000, 'Cross' : 4500} | ||
| values = sorted(dict_company.values())[-4 : -1] | ||
| for el in dict_company.items(): | ||
| for val in values: | ||
| if el[1] == val: | ||
| dict_profit.update({el}) | ||
| print(dict_profit) | ||
|
|
||
|
|
||
| # 2 | ||
| dict_profit = {} | ||
| dict_company = {'Yarl' : 3460, 'Quark' : 4000, 'Cityland' : 2690, 'Ion': 1000, 'Drink': 8000, 'Drank' : 34000, 'Cross' : 4500} | ||
| values = sorted(dict_company.values())[-4 : -1] | ||
| [dict_profit.update({el}) for el in dict_company.items() for val in values if el[1] == val] | ||
| print(dict_profit) | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. не описана где какая сложность |
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| """ | ||
| Задание 4. | ||
| Сама задача: | ||
| Пользователи веб-ресурса проходят аутентификацию. | ||
| В системе хранятся логин, пароль и отметка об активации учетной записи. | ||
| Нужно реализовать проверку, может ли пользователь быть допущен к ресурсу. | ||
| При этом его учетка должна быть активирована. | ||
| А если нет, то польз-лю нужно предложить ее пройти. | ||
| Приложение должно давать ответы на эти вопросы и быть реализовано в виде функции. | ||
| Для реализации хранилища можно применить любой подход, | ||
| который вы придумаете, например, реализовать словарь. | ||
| """ | ||
|
|
||
| # 1 способ | ||
| dict_logins = {'alex' : ['Password1', False], 'bob' : ['Password2', False], 'john' : ['Password3', True], 'helen' : ['Password4', True]} | ||
| login = input('Please provide login: ').lstrip().rstrip().lower() | ||
| password = input('Please provide password: ').lstrip().rstrip() | ||
|
|
||
| def authentificate (login, password): | ||
| login_info = dict_logins.get(login) | ||
| if login_info[0] != password: | ||
| print(f'You pvided wrong password. Bye') | ||
| return | ||
| if dict_logins.get(login)[1] == False: | ||
| answer_activate = input(f'You should acvate you login. Do it? Yes/No: ').lower() | ||
| if answer_activate == 'yes': | ||
| login_info[1] = True # activate login | ||
| dict_logins.update({login:login_info}) # put info dict | ||
| else: | ||
| print(f'You login {login} is activated. Welcome.') | ||
| return | ||
|
|
||
| authentificate (login, password) | ||
| print(dict_logins) | ||
|
|
||
| # 2 способ | ||
| # не придумал | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| """ | ||
| Задание 6. | ||
| Задание на закрепление навыков работы со стеком | ||
|
|
||
| Примечание: в этом задании вспомните ваши знания по работе с ООП | ||
| и опирайтесь на пример урока | ||
|
|
||
| Реализуйте структуру "стопка тарелок". | ||
|
|
||
| Мы можем складывать тарелки в стопку и при превышении некоторого значения | ||
| нужно начать складывать тарелки в новую стопку. | ||
|
|
||
| Структура должна предусматривать наличие нескольких стеков. | ||
| Создание нового стека происходит при достижении предыдущим стеком порогового значения. | ||
| Реализуйте по аналогии с примером, рассмотренным на уроке, необходимые методы, | ||
| для реализации это структуры, добавьте новые методы (не рассмотренные в примере с урока) | ||
| для реализации этой задачи. | ||
|
|
||
| После реализации структуры, проверьте ее работу на различных сценариях | ||
| """ | ||
|
|
||
| class StackClass: | ||
| def __init__(self, size): | ||
| self.size = size | ||
| self.curr_size = 0 | ||
| self.elems = [] | ||
|
|
||
| def push(self, el): | ||
| if self.curr_size == self.size: | ||
| return False | ||
| self.elems.append(el) | ||
| self.curr_size += 1 | ||
| return True | ||
|
|
||
| def pop(self): | ||
| self.curr_size -= 1 | ||
| return self.elems.pop() | ||
|
|
||
| def get(self, indx): | ||
| if indx >= self.get_size(): | ||
| return None | ||
| else: | ||
| return self.elems[indx] | ||
|
|
||
| def get_size(self): | ||
| return len(self.elems) | ||
|
|
||
| def __str__(self): | ||
| return str([elem for elem in self.elems]) | ||
|
|
||
| if __name__ == '__main__': | ||
| # Fill stacks | ||
| import random as rnd | ||
| SC_OBJ = [] # Stack array | ||
| SC_OBJ.append(StackClass(2)) | ||
| indx = 0 | ||
| for num in range(0, 30): | ||
| if SC_OBJ[indx].push(rnd.randint(1, 100)) == False: | ||
| SC_OBJ.append(StackClass(2)) | ||
| indx += 1 | ||
| else: | ||
| SC_OBJ[indx].push(rnd.randint(1, 100)) | ||
| # Read stacks and every component | ||
| for el in SC_OBJ: | ||
| print(el) | ||
| for indx in range(0, el.get_size()): | ||
| print(el.get(indx)) | ||
|
|
||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| """ | ||
| Задание 7. | ||
| Задание на закрепление навыков работы с очередью | ||
| Реализуйте структуру "доска задач". | ||
| Структура должна предусматривать наличие несольких очередей задач, например | ||
| 1) базовой, откуда задачи берутся, решаются и отправляются в список решенных | ||
| 2) очередь на доработку, когда нерешенные задачи из первой очереди отправляются | ||
| на корректировку решения | ||
| После реализации структуры, проверьте ее работу на различных сценариях | ||
| """ | ||
| class QueueClass: | ||
| def __init__(self): | ||
| self.elems = [] | ||
|
|
||
| def is_empty(self): | ||
| return self.elems == [] | ||
|
|
||
| def append(self, item): | ||
| self.elems.append(item) | ||
|
|
||
| def extract(self, indx): | ||
| return self.elems.pop(indx) | ||
|
|
||
| def size(self): | ||
| return len(self.elems) | ||
|
|
||
| def __str__(self): | ||
| return str([elem for elem in self.elems]) | ||
|
|
||
| if __name__ == '__main__': | ||
| queue_main = QueueClass() # Главная | ||
| queue_done = QueueClass() # Выполненные задачи | ||
| queue_change = QueueClass() # Требуется корректировка | ||
|
|
||
| # Loading tasks into queue_main | ||
| import random as rnd | ||
| for i in range(0, 21): | ||
| queue_main.append(rnd.randint(1, 100)) | ||
|
|
||
| # Moving tasks from queue_main to queue_done if task has been done | ||
| for i in range(0, 20, 2): | ||
| if queue_main.size() <= i: | ||
| break | ||
| elif queue_main.is_empty() != True: | ||
| queue_done.append(queue_main.extract(i)) | ||
| else: | ||
| print(f'Main queue is empty') | ||
|
|
||
| # Moving tasks from queue_main to queue_change if task required review | ||
| for i in range(0, 20, 2): | ||
| if queue_main.size() <= i: | ||
| break | ||
| elif queue_main.is_empty() != True: | ||
| queue_change.append(queue_main.extract(i)) | ||
| else: | ||
| print(f'Main queue is empty') | ||
|
|
||
| # Check if everuthing was done | ||
| if queue_main.is_empty() == True: | ||
| print(f'Your main queue is empty') | ||
| if queue_change.is_empty() == True: | ||
| print(f'Congratulation you have solved all your tasks') | ||
| else: | ||
| print(f'You have tasks for review {queue_change}') | ||
| else: | ||
| print(f'Your have not solved {queue_main.size()} tasks') | ||
| print(f'Thare are all {queue_main}') | ||
| print(f'Your have solved {queue_done} tasks') | ||
| print(f'Thare are task for review {queue_change}') | ||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| """ | ||
| Задание 5. | ||
| Задание на закрепление навыков работы с деком | ||
| В рассмотренном на уроке листинге есть один недостаток | ||
| Приведенный код способен "обработать" только строку без пробелов, например, 'топот' | ||
| Но могут быть и такие палиндромы, как 'молоко делили ледоколом' | ||
| Вам нужно доработать программу так, чтобы она могла выполнить проверку на палиндром | ||
| и в таких строках (включающих пробелы) | ||
| """ |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Александр, а где здесь решение?
его нет