-
Notifications
You must be signed in to change notification settings - Fork 0
Lesson3 #5
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
alardis
wants to merge
5
commits into
master
Choose a base branch
from
lesson3
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
Lesson3 #5
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
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,30 @@ | ||
| # Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. | ||
| # Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль. | ||
|
|
||
|
|
||
| def divider_self(local_a, local_b) -> float: | ||
| """ | ||
| Функция делит одно число на другое. Значение округляется для приятного вывода | ||
| :param local_a: int | ||
| :param local_b: int | ||
| :return: float | ||
| """ | ||
| # блок перехвата исключений | ||
| try: | ||
| local_a = int(local_a) | ||
| local_b = int(local_b) | ||
| result = round(local_a / local_b, 2) | ||
|
|
||
| return result | ||
| # обработка ситуации некорретного ввода | ||
| except ValueError: | ||
| print('Знаете, кажется, у вас проблемы с числами. Проверьте, пожалуйста.') | ||
| # обработка ситуации деления на ноль | ||
| except ZeroDivisionError: | ||
| print('Ох, как неловко вышло. Вы, кажется, только поделили на ноль. Не надо так.') | ||
|
|
||
|
|
||
| a = input(f'Введите число-делимое, пожалуйста\n') | ||
| b = input(f'Введите число-делитель, пожалуйста\n') | ||
|
|
||
| print(divider_self(a, b) or 'Нет результата') |
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,30 @@ | ||
| # Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя: | ||
| # имя, фамилия, год рождения, город проживания, email, телефон. | ||
| # Функция должна принимать параметры как именованные аргументы. Реализовать вывод данных о пользователе одной строкой | ||
|
|
||
|
|
||
| def user_data_func(**kwargs) -> str: | ||
| """ | ||
| Функция выводит параметры пользователя в одну строку | ||
| :param kwargs: dict | ||
| :return: str | ||
| """ | ||
| if kwargs: | ||
| result = '' | ||
| for key, value in kwargs.items(): | ||
| result += value + ', ' | ||
| result = result.strip(', ') | ||
|
|
||
| return result | ||
| else: | ||
| return 'У вас проблемы с данными о пользователе.' | ||
|
|
||
|
|
||
| print(user_data_func( | ||
| username='Ярослав', | ||
| surname='Иванов', | ||
| birthyear='1985', | ||
| usercity='Moscow', | ||
| email='ata@ata.ru', | ||
| phonenumber='+7916-555-55-55', | ||
| )) |
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,17 @@ | ||
| # Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших | ||
| # двух аргументов. | ||
|
|
||
|
|
||
| def sum_max(*args) -> int: | ||
| """ | ||
| Функция возвращает сумму двух наибольших аргументов из трех | ||
| :param args: int | ||
| :return: int | ||
| """ | ||
| if args and len(args) == 3: | ||
| return sum(args) - min(args) | ||
| else: | ||
| print('Проверьте состав передаваемого набора, пожалуйста') | ||
|
|
||
|
|
||
| print(sum_max(4, 5, 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,31 @@ | ||
| # Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить | ||
| # возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). При решении задания | ||
| # необходимо обойтись без встроенной функции возведения числа в степень. | ||
|
|
||
|
|
||
| def my_func(x, y) -> float: | ||
| """ | ||
| Возводит число x в степень y | ||
| :param x: float | ||
| :param y: int | ||
| :return: float | ||
| """ | ||
| try: | ||
| x = float(x) | ||
| y = int(y) | ||
| result = 1 | ||
| if x > 0 > y: | ||
| for i in range(-y): | ||
| print(f'Работаем с возведением в степень') | ||
| result = result * x | ||
| result = 1 / result | ||
| return result | ||
| else: | ||
| raise ValueError | ||
| except ValueError: | ||
| print('Что-то не так с набором чисел, проверьте') | ||
|
|
||
|
|
||
| a = input('Введите число Х, которое должно быть действительным и положительным\n') | ||
| b = input('Введите число Y, которое должно быть целым и отрицательным\n') | ||
| print(my_func(a, b)) |
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,44 @@ | ||
| # Программа запрашивает у пользователя строку чисел, разделенных пробелом. При нажатии Enter должна выводиться | ||
| # сумма чисел. Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter. | ||
| # Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме. Но если вместо числа вводится специальный | ||
| # символ, выполнение программы завершается. Если специальный символ введен после нескольких чисел, то вначале нужно | ||
| # добавить сумму этих чисел к полученной ранее сумме и после этого завершить программу. | ||
|
|
||
|
|
||
| import string | ||
|
|
||
| # помещать весь процесс в функцию нет никакого смысла | ||
| # соответственно, в функцию надо вынести исключительно атомарную операцию сложения строки | ||
| # функция будет возвращать второй параметр, говорящий, имеет ли смысл запрашивать еще одну строку, или все уже | ||
| # если в строке будет найден некорректный символ, второй параметр будет False | ||
|
|
||
|
|
||
| def sum_line(line, prev_sum): | ||
| """ | ||
| Считает сумму чисел в строке, проверяет, можно ли запрашивать еще одну строку на посчитать | ||
| :param line: str | ||
| :param prev_sum: int | ||
| :return: int, bool | ||
| """ | ||
| result = 0 | ||
| more = True | ||
| num_list = line.split(' ') | ||
|
|
||
| try: | ||
| for number in num_list: | ||
| if number not in string.punctuation: | ||
| result += int(number) | ||
| else: | ||
| more = False | ||
| break | ||
| return result + prev_sum, more | ||
| except ValueError: | ||
| print('Проверьте входной набор чисел') | ||
|
|
||
|
|
||
| another = True | ||
| current_sum = 0 | ||
| while another: | ||
| text_line = input('Введите строку чисел, разделенную пробелом\n') | ||
| current_sum, another = sum_line(text_line, current_sum) | ||
| print(f'Сумма чисел в строке: {current_sum}') |
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,21 @@ | ||
| # Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, | ||
| # но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text. | ||
| # Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом. Каждое слово | ||
| # состоит из латинских букв в нижнем регистре. Сделать вывод исходной строки, но каждое слово должно начинаться | ||
| # с заглавной буквы. Необходимо использовать написанную ранее функцию int_func(). | ||
|
|
||
|
|
||
| def int_func(local_word) -> str: | ||
| return local_word[0].upper() + local_word[1:] | ||
|
|
||
|
|
||
| # первая часть программы | ||
| print(int_func('text')) | ||
|
|
||
| # вторая часть программы | ||
| line = input('Введите строку текста маленькими латинскими буквами\n') | ||
| new_line = '' | ||
| for word in line.split(' '): | ||
| new_line += int_func(word) + ' ' | ||
| new_line = new_line.strip() | ||
| print(new_line) | ||
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,29 @@ | ||
| # Задача: написать функцию которая на вход принимает список с неопределенным уровнем вложенности других списков, | ||
| # например [1, 2, [3, 4, [5]], 6, [[[7, [8]]]]] | ||
| # Функция должна вернуть плоский список сохраняя последовательность [1, 2, 3, 4, 5, 6, 7, 8] | ||
|
|
||
|
|
||
| def list_convert(outerlist, item_to_check): | ||
| print(f"Рассматриваем элемент (начало): {item_to_check}") | ||
| if type(item_to_check) is list: | ||
| for i in item_to_check: | ||
| print(f"Рассматриваем элемент при вызове функции: {i}") | ||
| list_convert(outerlist, i) | ||
| else: | ||
| print(f"добавляем в список: {item_to_check}") | ||
| outerlist.append(item_to_check) | ||
|
|
||
|
|
||
| mylist = [] | ||
| list_to_plain = [1, 2, [3, 4, [5]], 6, [[[7, [8]]]]] | ||
| list_convert(mylist, list_to_plain) | ||
|
|
||
| print(mylist) | ||
|
|
||
| # а теперь попробуем то же самое с лямбдой | ||
| mylist1 = [] | ||
| lambda_plain = lambda item: mylist1.append(item) if type(item) is not list else [lambda_plain(i) for i in item] | ||
|
|
||
| [lambda_plain(i) for i in list_to_plain] | ||
|
|
||
| print(f"mylist1: {mylist1}") |
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.
старайтесь избегать конкатенации строк через сложение