-
Notifications
You must be signed in to change notification settings - Fork 260
basic excersise #26
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
base: main
Are you sure you want to change the base?
basic excersise #26
Conversation
MrAlekzI
commented
Feb 21, 2023
- Выполнил за 3 задания за вторую неделю, они же уровень 1 за третью
- бонусную задачу не смог запустить - почему то не найдена коллекция lorem, хотя я ее установил. Еще повожусь с ней
- Выполненная дополнительная задача из второй недели (про сортировки словарей) тоже здесь. Возможно есть какой-то более красивый и способ делать одновременную сортировку по двум ключам и значениям, причем по уменьшению и увеличению сразу (хотя это должно сильно усложнить по идее). Поэтому чтобы сортировать буквы которые встречаются одинаковое число раз я сначала перевел строку в список и отсортировал его, а потом перевел в словарь и отсортировал его. Вроде довольно быстро работает.
- задачи из уровня 2 и 3 добавлю по мере выполнения, чтобы все в последний момент не отправлять
|
dict_sorting_additional.py
Outdated
import random | ||
|
||
def letter_counter_dict(word): #решение 1 через словарь | ||
word_list = sorted(list(word)) #переводим в стисок и сортируем чтобы при одинкаовых количесвах буквы бли в алфавитном порядке |
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.
по идее сначала лучше посчитать, а потом сортировать, потому что меньше элементов скорей всего будет
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.
исправил - сначала посчитал словарь, потом провел две сортировки с ним по ключу и по значению
dict_sorting_additional.py
Outdated
for letter in word_list: #формируем словарь через get | ||
letter_dict[letter] = letter_dict.get(letter, 0) + 1 | ||
|
||
result = dict(sorted(letter_dict.items(), key=lambda item: item[1], reverse=True)) #сортировка по убыванию value |
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.
словари же сортированные в порядке добавления ключей. Зачем еще раз сортировать?
def letter_counter_dict_3(word): #решение 3 через Counter | ||
word_list = sorted(list(word)) | ||
letter_dict = Counter(word_list) | ||
result = letter_dict.most_common() |
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.
а тут точно по алфавиту выведет?
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.
Я проверил - да он сам делает по алфавиту
|
||
random_string = ''.join(random.choices(string.ascii_letters, k=100000)) | ||
print('Способ 1') | ||
letter_counter_dict(random_string) |
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.
лучше проверять не рандомными строками, а теми которые покрывают корнер кейсы
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.
исправил
ephem2_bot.py
Outdated
def user_request_moon(update, context): | ||
user_text = update.message.text.split() | ||
print(user_text) | ||
if len(user_text) == 2: |
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.
а что если длина будет больше?
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.
исправил
for_dict_challenges.py
Outdated
m+=1 | ||
else: | ||
f+=1 | ||
return (m,f) #здесь пробую кортеж чтобы не делать дополнительный словарь каждый раз |
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.
ну это не удобно. Надо не перепутать где какой пол лежит.
for_dict_challenges.py
Outdated
for clas in school: | ||
count_dict[clas['class']] = gender_count(clas["students"]) | ||
#здесь пожалуй воспользуюсь сортировкой | ||
boys = sorted(count_dict.items(), key=lambda item: item[1][0])[-1][0] |
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.
когда нужно одно значение, сортировка плохой выбор. Она сложнее
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.
сделас простой поиск маскимума в цикле
for_dict_challenges_bonus.py
Outdated
@@ -65,6 +66,75 @@ def generate_chat_history(): | |||
}) | |||
return messages | |||
|
|||
def max_count(some_dict): #здесь функция чтобы делать список элементов с максимальными значениями(на случай если не один ключ с максимальным значением) |
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.
some_dict - очень плохое имя. Вообще непонятно что это
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.
исправил
for message in lst: #словарь реплаев | ||
if message['reply_for']: | ||
reply_dict[message['reply_for']] = reply_dict.get(message['reply_for'], 0) + 1 | ||
for message in lst: #еще раз проходимся по списку и сверяем id со ключами словаря реплаев |
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.
а за один проход нельзя?
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.
переделал
for message in lst: | ||
user_dict[message['sent_by']] = user_dict.get(message['sent_by'], 0) + len(message['seen_by']) | ||
result = max_count(user_dict) | ||
return f'Наиболее просматриваемый пользователь(ли): {result}' |
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.
это ты нашел кто больше всего сообщений отправил
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.
не понял. почему, я же по ключу id пользователя увеличиваю значение на количество просмотров, да и проверил на нескольких запусках - показывает отличные от количества отправивших сообщение числа