-
Notifications
You must be signed in to change notification settings - Fork 77
Lesson_5 files #601
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_5
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
Lesson_5 files #601
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,83 @@ | ||
| """ | ||
| 1. Пользователь вводит данные о количестве предприятий, их наименования и прибыль | ||
| за 4 квартала (т.е. 4 отдельных числа) для каждого предприятия. | ||
| Программа должна определить среднюю прибыль (за год для всех предприятий) | ||
| и вывести наименования предприятий, чья прибыль выше среднего и отдельно | ||
| вывести наименования предприятий, чья прибыль ниже среднего. | ||
|
|
||
| Подсказка: | ||
| Для решения задачи обязательно примените какую-нибудь коллекцию из модуля collections | ||
| Для лучшее освоения материала можете даже сделать несколько решений этого задания, | ||
| применив несколько коллекций из модуля collections | ||
|
|
||
| Пример: | ||
| Введите количество предприятий для расчета прибыли: 2 | ||
| Введите название предприятия: Рога | ||
| через пробел введите прибыль данного предприятия | ||
| за каждый квартал(Всего 4 квартала): 235 345634 55 235 | ||
|
|
||
| Введите название предприятия: Копыта | ||
| через пробел введите прибыль данного предприятия | ||
| за каждый квартал(Всего 4 квартала): 345 34 543 34 | ||
|
|
||
| Средняя годовая прибыль всех предприятий: 173557.5 | ||
| Предприятия, с прибылью выше среднего значения: Рога | ||
|
|
||
| Предприятия, с прибылью ниже среднего значения: Копыта | ||
| """ | ||
|
|
||
|
|
||
| # Рога 235 345634 55 235 | ||
| # Копыта 345 34 543 34 | ||
|
|
||
| # Я использовал OrderedDict, правда не понимаю зачем здесь нужен любой объект из класса collections | ||
| from collections import OrderedDict as odict | ||
| import numpy as np | ||
|
|
||
| firm_profits = [] | ||
| firm_info = [] | ||
| num_firms = int(input('Plese provide number of rows: ').rstrip().lstrip()) | ||
| i = 0 | ||
| while i < num_firms: | ||
| dic = odict() | ||
| firm_name = str(input('Plese provide the name of firm: ').rstrip().lstrip()) | ||
| firm_profits = np.array((input('Plese provide the firm''s quarter profits separeted by spaces: ').rstrip().lstrip()).split(' '), dtype=int) | ||
| y_profit = np.sum(firm_profits) # Посчитать суммарный годовой доход | ||
| firm_profits = np.append(firm_profits, y_profit) # Добавит суммарный годовой доход в массив 5-ым элементом | ||
| dic.update({firm_name : firm_profits}) | ||
| firm_info.append(dic) | ||
| i += 1 | ||
|
|
||
| def sum_avg(): | ||
| profit = 0 | ||
| for firm in firm_info: | ||
| for item in firm.items(): | ||
| profit += item[1][4] | ||
| return profit / num_firms | ||
|
|
||
| all_avg = sum_avg() | ||
| for firm in firm_info: | ||
| for item in firm.items(): | ||
| if item[1][4] > all_avg: | ||
| print (f'Firm {item[0]} has average profit {item[1][4]} that is more than {all_avg}') | ||
| elif item[1][4] == all_avg: | ||
| print (f'Firm {item[0]} has average profit {item[1][4]} that is the same as {all_avg}') | ||
| else: | ||
| print (f'Firm {item[0]} has average profit {item[1][4]} that is less than {all_avg}') | ||
|
|
||
|
|
||
| """ | ||
| Plese provide number of rows: 2 | ||
| Plese provide the name of firm: Рога | ||
| Plese provide the firms quarter profits separeted by spaces: 235 345634 55 235 | ||
| Plese provide the name of firm: Копыта | ||
| Plese provide the firms quarter profits separeted by spaces: 345 34 543 34 | ||
| Firm Рога has average profit 346159 that is more than 173557.5 | ||
| Firm Копыта has average profit 956 that is less than 173557.5 | ||
| """ | ||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
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,42 @@ | ||
| """ | ||
| 2. Написать программу сложения и умножения двух шестнадцатеричных чисел. | ||
| При этом каждое число представляется как массив, элементы которого это цифры числа. | ||
| Например, пользователь ввёл A2 и C4F. Сохранить их как [‘A’, ‘2’] и [‘C’, ‘4’, ‘F’] соответственно. | ||
| Сумма чисел из примера: [‘C’, ‘F’, ‘1’], произведение - [‘7’, ‘C’, ‘9’, ‘F’, ‘E’]. | ||
|
|
||
| Подсказка: | ||
| Для решения задачи обязательно примените какую-нибудь коллекцию из модуля collections | ||
| Для лучшее освоения материала можете даже сделать несколько решений этого задания, | ||
| применив несколько коллекций из модуля collections | ||
| Также попробуйте решить задачу вообще без collections и применить только ваши знания по ООП | ||
| (в частности по перегрузке методов) | ||
| """ | ||
|
|
||
|
|
||
|
|
||
| class Hex: | ||
| def __init__(self, x): | ||
| self.list = list(x) | ||
| self.x = str(x) | ||
|
|
||
| def __str__(self): | ||
| return str(self.x) | ||
|
|
||
| def __add__(self, obj): | ||
| return hex(int(self.x, 16) + int(str(obj), 16))[2:].upper() | ||
|
|
||
| def __sub__(self, obj): | ||
| return hex(int(self.x, 16) - int(str(obj), 16))[2:].upper() | ||
|
|
||
| def __mul__(self, obj): | ||
| return hex(int(self.x, 16) * int(str(obj), 16))[2:].upper() | ||
|
|
||
|
|
||
|
|
||
| hex1 = Hex('A2') | ||
| hex2 = Hex('C4F') | ||
| print(hex1 + hex2) | ||
| print(hex2 - hex1) | ||
| print(hex1 * hex2) | ||
|
|
||
| # Я не придумал к чему тут применить collections, а классы - пожалуйста :) | ||
|
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,57 @@ | ||
| """ | ||
| Задача 3. | ||
| В соответствии с документацией Python, | ||
| deque – это обобщение стеков и очередей. | ||
| Вот основное правило: если вам нужно что-то быстро дописать или вытащить, используйте deque. | ||
| Если вам нужен быстрый случайный доступ, используйте list. | ||
|
|
||
| Задача: создайте простой список (list) и очередь (deque). | ||
| Выполните различные операции с каждым из объектов. | ||
| Сделайте замеры и оцените, насколько информация в документации | ||
| соответствует дейстивтельности. | ||
| """ | ||
| from collections import deque | ||
| from random import randint | ||
| import timeit | ||
|
|
||
| src = [randint(1, 100) for i in range(1, 10000)] | ||
| queue = deque(src) | ||
|
|
||
|
|
||
| def insert_list(indx, val): | ||
| src.insert(indx, val) | ||
|
|
||
| def insert_queue(indx, val): | ||
| queue.insert(indx, val) | ||
|
|
||
| indx = 123 | ||
| val = 9999 | ||
| print(timeit.timeit("insert_list(indx, val)", setup="from __main__ import insert_list, indx, val", number=1000)) | ||
| print(timeit.timeit("insert_queue(indx, val)", setup="from __main__ import insert_queue, indx, val", number=1000)) | ||
| """ | ||
| 0.006530399999999999 | ||
| 0.00037399999999999933 | ||
| """ | ||
| # Вывод вставка в deque происходит быстрее | ||
|
|
||
| def get_from_list(indx): | ||
| return src[indx] | ||
|
|
||
| def get_from_queue(indx): | ||
| i = 0 | ||
| for val in queue: | ||
| if i == indx: | ||
| return val | ||
| else: | ||
| i += 1 | ||
|
|
||
|
|
||
| indx = 123 | ||
| print(timeit.timeit("get_from_list(indx)", setup="from __main__ import get_from_list, indx", number=1000)) | ||
| print(timeit.timeit("get_from_queue(indx)", setup="from __main__ import get_from_queue, indx", number=1000)) | ||
|
|
||
| """ | ||
| 8.289999999999687e-05 | ||
| 0.005491299999999998 | ||
| """ | ||
| # поиск по индексу в list значительно быстрее |
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,48 @@ | ||
| """ | ||
| Задача 4. | ||
| Поработайте с обычным словарем и OrderedDict. | ||
| Выполните различные операции с каждым из объектов и сделайте замеры. | ||
| Опишите полученные результаты, сделайте выводы. | ||
| """ | ||
| from collections import OrderedDict | ||
| import timeit | ||
|
|
||
| us_dict = {'z' : 2, 'b' : 8, 'c' : 10, 'd' : 12, 'a' : 45} | ||
| or_dict = OrderedDict() | ||
| or_dict = {'z' : 2, 'b' : 8, 'c' : 10, 'd' : 12, 'a' : 45} | ||
|
|
||
| def us_dict_update(key, val): | ||
| us_dict.update({key : val}) | ||
|
|
||
| def or_dict_update(key, val): | ||
| or_dict.update({key : val}) | ||
|
|
||
|
|
||
| key = 'r' | ||
| val = 888 | ||
| print(timeit.timeit("us_dict_update(key, val)", setup="from __main__ import us_dict_update, key, val", number=1000)) | ||
| print(timeit.timeit("or_dict_update(key, val)", setup="from __main__ import or_dict_update, key, val", number=1000)) | ||
| """ | ||
| 0.00022180000000000116 | ||
| 0.0002420999999999951 | ||
| """ | ||
| # Время обновления почти одинаково | ||
|
|
||
|
|
||
| def us_dict_get(key): | ||
| return us_dict.get(key) | ||
|
|
||
| def or_dict_get(key): | ||
| return or_dict.get(key) | ||
|
|
||
|
|
||
| key = 'a' | ||
| print(timeit.timeit("us_dict_get(key)", setup="from __main__ import us_dict_get, key", number=1000)) | ||
| print(timeit.timeit("or_dict_get(key)", setup="from __main__ import or_dict_get, key", number=1000)) | ||
| """ | ||
| 0.00011160000000000336 | ||
| 0.00011830000000000174 | ||
| """ | ||
| # Время выполнения get почти одинаково | ||
|
|
||
| # Я не вижу преимуществ у OrderedDict |
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.
упрощает обработку данных
в данном случае хорошо вписывает namedtuple
а вот зачем OrderedDict не совсем понимаю?
словари сейчас уже упорядоченные