-
Notifications
You must be signed in to change notification settings - Fork 77
Lesson_2 files #597
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_2
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_2 files #597
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,60 @@ | ||
| # Написать программу, которая будет складывать, вычитать, умножать или делить два числа. Числа и знак операции вводятся пользователем. | ||
| # После выполнения вычисления программа не должна завершаться, а должна запрашивать новые данные для вычислений. | ||
| # Завершение программы должно выполняться при вводе символа '0' в качестве знака операции. | ||
| # Если пользователь вводит неверный знак (не '0', '+', '-', '*', '/'), то программа должна сообщать ему об ошибке и снова запрашивать знак операции. | ||
| # Также сообщать пользователю о невозможности деления на ноль, если он ввел 0 в качестве делителя. | ||
|
|
||
| # Я преписал это как калькулятор. | ||
| # Извините | ||
| def is_number(str): | ||
| try: | ||
| float(str) | ||
| return True | ||
| except ValueError: | ||
| return False | ||
|
|
||
| def checkinput(inpstr): | ||
| math_sins = '+' '-' '*' '/' | ||
| num1, sign, num2 = inpstr.split(' ') | ||
| result = True | ||
| if not is_number(num1): | ||
| print(f'{num1} is not number') | ||
| result = False | ||
| if not is_number(num2): | ||
| print(f'{num2} is not number') | ||
| result = False | ||
| if math_sins.find(sign) == -1: | ||
| print(f'{sign} is not allowed math operator.') | ||
| result = False | ||
| return result | ||
|
|
||
| def math_op(inpstr): | ||
| result = '' | ||
| num1, sign, num2 = inpstr.split(' ') | ||
| num1 = float(num1) | ||
| num2 = float(num2) | ||
| if sign == '+': | ||
| result = str(num1 + num2) | ||
| elif sign == '-': | ||
| result = str(num1 - num2) | ||
| elif sign == '*': | ||
| result = str(num1 * num2) | ||
| elif sign == '/': | ||
| if num2 != 0: | ||
| result = str(num1 / num2) | ||
| else: | ||
| result = 'N/A trying to divide by 0' | ||
| return result | ||
|
|
||
|
|
||
|
|
||
| while True: | ||
| print('Please provide what you want to do. Fo instance "12 + 25 = <Enter>" : ') | ||
| inp_str = input('Number and signs please split by space. For cancell type "q" ').lstrip().rstrip() | ||
| if inp_str == 'q': | ||
| break | ||
| if inp_str.count(' ') != 2: | ||
| print('Error. Your provided not 3 values') | ||
| break | ||
| if checkinput(inp_str): | ||
| print(f'The result {inp_str} = {math_op(inp_str)}') | ||
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 @@ | ||
| """ | ||
| 2. Посчитать четные и нечетные цифры введенного натурального числа. | ||
| Например, если введено число 34560, то у него 3 четные цифры | ||
| (4, 6 и 0) и 2 нечетные (3 и 5). | ||
|
|
||
| Подсказка: | ||
| На каждом шаге вам нужно 'доставать' из числа очередную цифру | ||
| и смотреть является ли она четной или нечетной. При этом увеличиваем соответствующий счетчик | ||
| Пока все числа не извлечены рекурсивные вызовы продолжаем | ||
| Условие завершения рекурсии - все числа извлечены | ||
| Используем операции % // | ||
|
|
||
| Решите через рекурсию. Решение через цикл не принимается. | ||
| Для оценки Отлично в этом блоке необходимо выполнить 5 заданий из 7 | ||
|
|
||
| Пример: | ||
| Введите число: 123 | ||
| Количество четных и нечетных цифр в числе равно: (1, 2) | ||
| """ | ||
|
|
||
|
|
||
| def odd(number): | ||
| count_odd = 0 | ||
| numdig = len(str(number)) | ||
| dig = number % 10 | ||
| if dig % 2: | ||
| count_odd += 1 | ||
| if numdig != 1: | ||
| return count_odd + odd(number // 10) | ||
| else: | ||
| return count_odd | ||
|
|
||
| def even_odd(number): | ||
| numdig = len(str(number)) | ||
| count_odd = odd(number) | ||
| count_even = numdig - count_odd | ||
| return count_even, count_odd | ||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
| print (even_odd(1233333)) |
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 @@ | ||
| """ | ||
| Сформировать из введенного числа обратное по порядку входящих в него | ||
| цифр и вывести на экран. Например, если введено число 3486, | ||
| то надо вывести число 6843. | ||
|
|
||
| Подсказка: | ||
| На каждом шаге вам нужно 'доставать' из числа очередную цифру | ||
| Пока все числа не извлечены рекурсивные вызовы продолжаем | ||
| Условие завершения рекурсии - все цифры извлечены | ||
| Используем операции % // | ||
|
|
||
| Решите через рекурсию. Решение через цикл не принимается. | ||
| Для оценки Отлично в этом блоке необходимо выполнить 5 заданий из 7 | ||
|
|
||
| Пример: | ||
| Введите число, которое требуется перевернуть: 123 | ||
| Перевернутое число: 321 | ||
| """ | ||
|
|
||
|
|
||
| def reverse_digits(number): | ||
| rev = str(number % 10) | ||
| if number != 0: | ||
| return rev + reverse_digits(number // 10) | ||
| else: | ||
| return '' | ||
|
|
||
| print(reverse_digits(123)) | ||
|
|
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,32 @@ | ||
| """ | ||
| Найти сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ... | ||
| Количество элементов (n) вводится с клавиатуры. | ||
|
|
||
| Пример: | ||
| Введите количество элементов: 3 | ||
| Количество элементов - 3, их сумма - 0.75 | ||
|
|
||
| Решите через рекурсию. Решение через цикл не принимается. | ||
| Для оценки Отлично в этом блоке необходимо выполнить 5 заданий из 7 | ||
|
|
||
| Ряд строить программно - в самой же рекурсивной ф-ции | ||
| или даже обойтисть без создания ряда | ||
|
|
||
| Элемент в 2 раза меньше предыд и имеет противопол знак | ||
| """ | ||
|
|
||
| def sum_of_set(number): | ||
| result = 0 | ||
| if number % 2: | ||
| result += 1 / (2 ** (number-1)) | ||
| else: | ||
| result -= 1 / (2 ** (number-1)) | ||
| if number > 1: | ||
| return result + sum_of_set(number - 1) | ||
| else: | ||
| return result | ||
|
|
||
|
|
||
| print(sum_of_set(3)) | ||
|
|
||
|
|
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,40 @@ | ||
| """ | ||
| Вывести на экран коды и символы таблицы ASCII, начиная с символа | ||
| под номером 32 и заканчивая 127-м включительно. | ||
| Вывод выполнить в табличной форме: по десять пар "код-символ" в каждой строке. | ||
|
|
||
| Пример: | ||
| 32 - 33 - ! 34 - " 35 - # 36 - $ 37 - % 38 - & 39 - ' 40 - ( 41 - ) | ||
| 42 - * 43 - + 44 - , 45 - - 46 - . 47 - / 48 - 0 49 - 1 50 - 2 51 - 3 | ||
| 52 - 4 53 - 5 54 - 6 55 - 7 56 - 8 57 - 9 58 - : 59 - ; 60 - < 61 - = | ||
| 62 - > 63 - ? 64 - @ 65 - A 66 - B 67 - C 68 - D 69 - E 70 - F 71 - G | ||
| 72 - H 73 - I 74 - J 75 - K 76 - L 77 - M 78 - N 79 - O 80 - P 81 - Q | ||
| 82 - R 83 - S 84 - T 85 - U 86 - V 87 - W 88 - X 89 - Y 90 - Z 91 - [ | ||
| 92 - \ 93 - ] 94 - ^ 95 - _ 96 - ` 97 - a 98 - b 99 - c 100 - d 101 - e | ||
| 102 - f 103 - g 104 - h 105 - i 106 - j 107 - k 108 - l 109 - m 110 - n 111 - o | ||
| 112 - p 113 - q 114 - r 115 - s 116 - t 117 - u 118 - v 119 - w 120 - x 121 - y | ||
| 122 - z 123 - { 124 - | 125 - } 126 - ~ 127 - | ||
|
|
||
| Решите через рекурсию. Решение через цикл не принимается. | ||
| Для оценки Отлично в этом блоке необходимо выполнить 5 заданий из 7 | ||
| Допускается исп-е встроенных ф-ций | ||
| """ | ||
|
|
||
| def symbols(scode = 32): | ||
| str_result = '' | ||
| if scode == 32 or scode == 127: | ||
| val = ' ' | ||
| else: | ||
| val = chr(scode) | ||
| if int(str(scode)[-1]) == 1: | ||
| str_result = ' ' + str_result + str(scode) + ' - ' + val + '\n' | ||
| else: | ||
| str_result = ' ' + str_result + str(scode) + ' - ' + val | ||
| if scode < 127: | ||
| return str_result + (symbols(scode + 1)) | ||
| else: | ||
| return str_result | ||
|
|
||
|
|
||
| result = symbols() | ||
| print(result) | ||
|
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. (symbols(scode + 1)) |
||
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 @@ | ||
| """ | ||
| Напишите программу, доказывающую или проверяющую, что для множества | ||
| натуральных чисел выполняется равенство: 1+2+...+n = n(n+1)/2, | ||
| где n - любое натуральное число. | ||
| Решите через рекурсию. Решение через цикл не принимается. | ||
| Для оценки Отлично в этом блоке необходимо выполнить 5 заданий из 7 | ||
| """ | ||
|
|
||
| def arith_seq(number): | ||
| if number != 0: | ||
| return number + arith_seq(number-1) | ||
| else: | ||
| return number | ||
|
|
||
|
|
||
| print (arith_seq(4)) | ||
|
|
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.
задание не выполнено
рекурсия отсутствует