Skip to content

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open

basic excersise #26

wants to merge 4 commits into from

Conversation

MrAlekzI
Copy link

  1. Выполнил за 3 задания за вторую неделю, они же уровень 1 за третью
  2. бонусную задачу не смог запустить - почему то не найдена коллекция lorem, хотя я ее установил. Еще повожусь с ней
  3. Выполненная дополнительная задача из второй недели (про сортировки словарей) тоже здесь. Возможно есть какой-то более красивый и способ делать одновременную сортировку по двум ключам и значениям, причем по уменьшению и увеличению сразу (хотя это должно сильно усложнить по идее). Поэтому чтобы сортировать буквы которые встречаются одинаковое число раз я сначала перевел строку в список и отсортировал его, а потом перевел в словарь и отсортировал его. Вроде довольно быстро работает.
  4. задачи из уровня 2 и 3 добавлю по мере выполнения, чтобы все в последний момент не отправлять

@MrAlekzI
Copy link
Author

  1. Выложил бонусную задачу про словари с прошлой недели
  2. Бот для подсчета слов - воспользовался regex чтобы упростить и не писать много условий
  3. Дополненный ephem бот с функцией определения даты полнолуния + заменил eval на getattr и привел даты к одинаковому форматированию для функционала из предыдущей версии бота (старой версии нет в этом репозитории - она в другом)

import random

def letter_counter_dict(word): #решение 1 через словарь
word_list = sorted(list(word)) #переводим в стисок и сортируем чтобы при одинкаовых количесвах буквы бли в алфавитном порядке

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.

исправил - сначала посчитал словарь, потом провел две сортировки с ним по ключу и по значению

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

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()

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.

Я проверил - да он сам делает по алфавиту


random_string = ''.join(random.choices(string.ascii_letters, k=100000))
print('Способ 1')
letter_counter_dict(random_string)

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.

исправил

ephem2_bot.py Outdated
def user_request_moon(update, context):
user_text = update.message.text.split()
print(user_text)
if len(user_text) == 2:

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.

исправил

m+=1
else:
f+=1
return (m,f) #здесь пробую кортеж чтобы не делать дополнительный словарь каждый раз

Choose a reason for hiding this comment

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

ну это не удобно. Надо не перепутать где какой пол лежит.

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]

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.

сделас простой поиск маскимума в цикле

@@ -65,6 +66,75 @@ def generate_chat_history():
})
return messages

def max_count(some_dict): #здесь функция чтобы делать список элементов с максимальными значениями(на случай если не один ключ с максимальным значением)

Choose a reason for hiding this comment

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

some_dict - очень плохое имя. Вообще непонятно что это

Copy link
Author

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 со ключами словаря реплаев

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.

переделал

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}'

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.

не понял. почему, я же по ключу id пользователя увеличиваю значение на количество просмотров, да и проверил на нескольких запусках - показывает отличные от количества отправивших сообщение числа

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy