-
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| # Byte-compiled / optimized / DLL files | ||
| __pycache__/ | ||
| *.py[cod] | ||
| *$py.class | ||
|
|
||
| # C extensions | ||
| *.so | ||
|
|
||
| # Distribution / packaging | ||
| .Python | ||
| build/ | ||
| develop-eggs/ | ||
| dist/ | ||
| downloads/ | ||
| eggs/ | ||
| .eggs/ | ||
| lib/ | ||
| lib64/ | ||
| parts/ | ||
| sdist/ | ||
| var/ | ||
| wheels/ | ||
| pip-wheel-metadata/ | ||
| share/python-wheels/ | ||
| *.egg-info/ | ||
| .installed.cfg | ||
| *.egg | ||
| MANIFEST | ||
|
|
||
| # PyInstaller | ||
| # Usually these files are written by a python script from a template | ||
| # before PyInstaller builds the exe, so as to inject date/other infos into it. | ||
| *.manifest | ||
| *.spec | ||
|
|
||
| # Installer logs | ||
| pip-log.txt | ||
| pip-delete-this-directory.txt | ||
|
|
||
| # Unit test / coverage reports | ||
| htmlcov/ | ||
| .tox/ | ||
| .nox/ | ||
| .coverage | ||
| .coverage.* | ||
| .cache | ||
| nosetests.xml | ||
| coverage.xml | ||
| *.cover | ||
| .hypothesis/ | ||
| .pytest_cache/ | ||
|
|
||
| # Translations | ||
| *.mo | ||
| *.pot | ||
|
|
||
| # Django stuff: | ||
| *.log | ||
| local_settings.py | ||
| db.sqlite3 | ||
|
|
||
| # Flask stuff: | ||
| instance/ | ||
| .webassets-cache | ||
|
|
||
| # Scrapy stuff: | ||
| .scrapy | ||
|
|
||
| # Sphinx documentation | ||
| docs/_build/ | ||
|
|
||
| # PyBuilder | ||
| target/ | ||
|
|
||
| # Jupyter Notebook | ||
| .ipynb_checkpoints | ||
|
|
||
| # IPython | ||
| profile_default/ | ||
| ipython_config.py | ||
|
|
||
| # pyenv | ||
| .python-version | ||
|
|
||
| # pipenv | ||
| # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. | ||
| # However, in case of collaboration, if having platform-specific dependencies or dependencies | ||
| # having no cross-platform support, pipenv may install dependencies that don't work, or not | ||
| # install all needed dependencies. | ||
| #Pipfile.lock | ||
|
|
||
| # celery beat schedule file | ||
| celerybeat-schedule | ||
|
|
||
| # SageMath parsed files | ||
| *.sage.py | ||
|
|
||
| # Environments | ||
| .env | ||
| .venv | ||
| env/ | ||
| venv/ | ||
| ENV/ | ||
| env.bak/ | ||
| venv.bak/ | ||
|
|
||
| # Spyder project settings | ||
| .spyderproject | ||
| .spyproject | ||
|
|
||
| # Rope project settings | ||
| .ropeproject | ||
|
|
||
| # mkdocs documentation | ||
| /site | ||
|
|
||
| # mypy | ||
| .mypy_cache/ | ||
| .dmypy.json | ||
| dmypy.json | ||
|
|
||
| # Pyre type checker | ||
| .pyre/ | ||
|
|
||
| #Files | ||
| settings.py |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| ''' | ||
| Дополнительное задание: | ||
| Посчитать число буквв слове и вывести начиная с самой часто встречающейся и дльше по убыванию. | ||
| Если несколько букв встречаются в слове одинаковое число раз, | ||
| то вывести вперед ту что раньше в алфавите. Написать три решения - использую просто словарь, defaultdict и Counter. | ||
| ''' | ||
| from collections import defaultdict, Counter | ||
| import string | ||
| import random | ||
|
|
||
| def letter_counter_dict(word): #решение 1 через словарь | ||
| #word_list = sorted(list(word)) #переводим в стисок и сортируем чтобы при одинкаовых количесвах буквы бли в алфавитном порядке | ||
| letter_dict = {} | ||
| for letter in word: #формируем словарь через get | ||
| letter_dict[letter] = letter_dict.get(letter, 0) + 1 | ||
|
|
||
| result1 = sorted(letter_dict.items(), key=lambda item: item[0]) #сортировка по алфафиту после подсчета | ||
| result2 = sorted(result1, key=lambda item: item[1], reverse=True) #обратная сортировка по значению | ||
| for (key, value) in result2: | ||
| print(key, value, end=' ') | ||
|
|
||
| def letter_counter_dict_2(word): #решение 2 через defaultdict | ||
| #word_list = sorted(list(word)) | ||
| letter_dict = defaultdict(lambda: 0) #задаем дефолное значения ключа | ||
| for letter in word: #формируем словарь | ||
| letter_dict[letter] += 1 | ||
|
|
||
| result1 = sorted(letter_dict.items(), key=lambda item: item[0]) #сортировка по алфафиту после подсчета | ||
| result2 = sorted(result1, key=lambda item: item[1], reverse=True) #обратная сортировка по значению | ||
| for (key, value) in result2: | ||
| print(key, value, end=' ') | ||
|
|
||
| def letter_counter_dict_3(word): #решение 3 через Counter | ||
| word_list = sorted(list(word)) | ||
| letter_dict = Counter(word_list) | ||
| result = letter_dict.most_common() | ||
| for (key, value) in result: | ||
| print(key, value, end=' ') | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
|
|
||
| random_string = 'pnbalkpanactlnca' | ||
| #test_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 commentThe reason will be displayed to describe this comment to others. Learn more. лучше проверять не рандомными строками, а теми которые покрывают корнер кейсы
Author
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. исправил |
||
| print ('\nСпособ 2') | ||
| letter_counter_dict_2(random_string) | ||
| print ('\nСпособ 3') | ||
| letter_counter_dict_3(random_string) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| ''' | ||
| Изменени: | ||
| 1.Добавлена команда для получении информации о дате следующего полнолуния: | ||
| Реализуйте в боте команду, которая отвечает на вопрос “Когда ближайшее полнолуние?” | ||
| Например /next_full_moon 2019-01-01. Чтобы узнать, когда ближайшее полнолуние, используйте ephem.next_full_moon(ДАТА) | ||
|
|
||
| 2. убрана реализация выбора объекта класса через eval - заменено на getattr() | ||
| 3. унифицировано форматирование дат при выводе сообщения пользователю | ||
| ''' | ||
|
|
||
| import ephem | ||
| import logging | ||
| import settings | ||
| from telegram.ext import Updater, CommandHandler, MessageHandler, Filters | ||
| from datetime import date, datetime | ||
|
|
||
| logging.basicConfig(format='%(name)s - %(levelname)s - %(message)s', | ||
| level=logging.INFO, | ||
| filename='bot.log') | ||
|
|
||
|
|
||
| def greet_user(update, context): | ||
| text = 'Вызван /start \n введите /planet объект ДД/MM/ГГГГ,\ | ||
| или только объект, если хотите узнать про сегодня \ | ||
| или введите /next_moon (ДАТА), чтобы узнать дату следующего полнолуния' | ||
| print(text) | ||
| update.message.reply_text(text) | ||
|
|
||
| # для нижеописанной функции если через date.today() то форматирование значения по умолчанию не работает в боте\ | ||
| # , решил не связываться с престановкой вызваных атрибутов в f-string при return | ||
|
|
||
| def constellation (planet, user_date): | ||
| try: | ||
| planet_type = getattr(ephem, planet.capitalize()) | ||
| planet_time = planet_type(user_date) | ||
| #planet_time = eval(f'ephem.{planet.capitalize()}("{user_date}")') | ||
| #planet_time = onvertion = exec(f'ephem.{planet}("{date}")') #это почему то не работает | ||
| return f'Планета {planet.capitalize()} на дату {user_date} проходит в созвездии {ephem.constellation(planet_time)[1]}' | ||
| except (TypeError, AttributeError): | ||
| return 'Вы выбрали не зодиакальный объект' | ||
|
|
||
| def user_moon(user_date): | ||
| full_moon_date = ephem.next_full_moon(user_date) | ||
| return f'Следующее полнолуние будет {full_moon_date}' | ||
|
|
||
| def user_request_const(update, context): | ||
| user_text = update.message.text.split() | ||
| print(user_text) | ||
| if len(user_text) >= 3: | ||
| user_date = user_text[2] | ||
| elif len(user_text) == 2: | ||
| user_date = datetime.now().strftime('%d/%m/%y') | ||
| update.message.reply_text(constellation(user_text[1], user_date)) | ||
|
|
||
| def user_request_moon(update, context): | ||
| user_text = update.message.text.split() | ||
| print(user_text) | ||
| if len(user_text) >= 2: | ||
| user_date = user_text[2] | ||
| elif len(user_text) == 1: | ||
| user_date = datetime.now().strftime('%d/%m/%y') | ||
| update.message.reply_text(user_moon(user_date)) | ||
|
|
||
|
|
||
|
|
||
|
|
||
| def main(): | ||
| mybot = Updater(settings.TOKEN_ephem, use_context=True) | ||
|
|
||
| dp = mybot.dispatcher | ||
| dp.add_handler(CommandHandler("start", greet_user)) | ||
| dp.add_handler(CommandHandler("planet", user_request_const)) | ||
| dp.add_handler(CommandHandler("next_moon", user_request_moon)) | ||
| dp.add_handler(MessageHandler(Filters.text, user_request_const)) | ||
|
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. хэндлеры по тексту, взаимоисключающие. ТОлько один из них будет работать. |
||
| dp.add_handler(MessageHandler(Filters.text, user_request_moon)) | ||
|
|
||
| mybot.start_polling() | ||
| mybot.idle() | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,7 +2,8 @@ | |
| # Необходимо вывести имена всех учеников из списка с новой строки | ||
|
|
||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| # ??? | ||
| for person in names: | ||
| print(person) | ||
|
|
||
|
|
||
| # Задание 2 | ||
|
|
@@ -12,7 +13,8 @@ | |
| # Петя: 4 | ||
|
|
||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| # ??? | ||
| for person in names: | ||
| print(f'{person}: {len(person)}') | ||
|
|
||
|
|
||
| # Задание 3 | ||
|
|
@@ -25,7 +27,9 @@ | |
| 'Маша': False, | ||
| } | ||
| names = ['Оля', 'Петя', 'Вася', 'Маша'] | ||
| # ??? | ||
| for person in names: | ||
| print(f'{person}: {"M" if is_male[person] else "Ж"}') | ||
|
|
||
|
|
||
|
|
||
| # Задание 4 | ||
|
|
@@ -40,7 +44,9 @@ | |
| ['Вася', 'Маша', 'Саша', 'Женя'], | ||
| ['Оля', 'Петя', 'Гриша'], | ||
| ] | ||
| # ??? | ||
| print(f'Всего {len(groups)} группы') | ||
| for i in range (len(groups)): | ||
|
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. лучше enumerate использовать |
||
| print(f'Группа {i+1}: {len(groups[i])} ученика') # если бы не частынй случай то нужно было делать функцию которая бы меняла окончания слов | ||
|
|
||
|
|
||
| # Задание 5 | ||
|
|
@@ -54,4 +60,5 @@ | |
| ['Оля', 'Петя', 'Гриша'], | ||
| ['Вася', 'Маша', 'Саша', 'Женя'], | ||
| ] | ||
| # ??? | ||
| for i in range (len(groups)): | ||
| print(f'Группа {i+1}: {", ".join(map(str, groups[i]))}') | ||
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.
Я проверил - да он сам делает по алфавиту