def bank(): """Calculating the deposit. Input arguments: sum, percent, time, must be integers. Output: amount of money on the deposit. """ def deposit(a, b, c): """Deposit calculation function""" for i in range(time): dep = (sum + (sum * percent) / 100) return dep while True: try: sum = int(m.text("Введите размер взноса: ")) percent = int(m.text("Введите банковский процент: ")) time = int(m.text("Введите количество месяцев: ")) except: print('Еще раз') continue else: print(f"""Предполагаемая сумма денег на вкладе: {deposit(sum, percent, time)}""") break
def sort(): """Bubble sort of generated list of numbers. Input arguments: number of elements of list, must be int. Output: list sorted in ascending order. """ def bubble(list): """List sorting implementation.""" for i in range(n - 1): for j in range(n - i - 1): if list[j] > list[j + 1]: list[j], list[j + 1] = list[j + 1], list[j] n = m.text("Введите количество элементов в списке: ") if n.isdigit(): n = int(n) l = [] for i in range(n): l.append(randint(1, 99)) print(f"Сгенерированный список: {l}") bubble(l) print(f"Отсортированый список: {l}") else: print("Неверный ввод, введите положительное число")
def fact(): """Calculating the factorial of a number using a function. Input arguments: n, must be integer. Output: factorial of a number. """ def factorial(n): "Calculating the factorial of a number without recursion" fact = 1 for i in range(1, n + 1): fact *= i return fact while True: try: n = int( m.text("""Введите натуральное число для вычисления факториала: """)) except: print('Еще раз') continue else: print(f"Факториал равен: {factorial(n)}") break
def freq(): """Counting the frequency of characters in the text. Input arguments: text, must be string. Output: dictionary of symbols. """ text = (m.text("Введите строку: ")) print((lambda res: Counter(res))(text))
def fact(): """Calculating factorial without using recursion. Input arguments: n, must be an integer. Output: factorial of number n. """ n = int(m.text('Введите натуральное число для вычисления факториала: ')) print((lambda a: math.factorial(a))(n))
def sentences(): """Counting the number of sentences in the text. Input arguments: text, must be string. Output: sentences count. """ text = (m.text("Введите текст: ")) a = text.count('. ') + text.count('! ') + text.count('? ') + 1 print(f"Количество предложений в тексте: {a}")
def words(): """Counting the number of words in the text. Input arguments: text, must be string. Output: word count. """ str = (m.text("Введите текст: ")) n = len(str.split()) print(f"Количество слов в тексте: {n}")
def fact(): """Calculating the factorial of a number using a recursion. Input arguments: n, must be integer. Output: factorial of a number. """ n = int(m.text('Введите натуральное число для вычисления факториала: ')) fact = lambda n: 1 if n < 1 else n * fact(n - 1) print(fact(n))
def del_same(): """Removes duplicate items from the list. Input arguments: list of elements. Output: list without duplicates. """ l = [ str(i) for i in m.text('Введите элементы списка через пробел: ').split() ] print(f"Первоначальный список : {str(l)}") print(f"Список без повторений: {list(set(l))}")
def coinc(): """Checking the list for matching elements. Input arguments: list1, list2. elements must be string. Output: match message. """ list1 = [ str(i) for i in m.text( 'Введите элементы первого списка через пробел: ').split() ] list2 = [ str(i) for i in m.text( 'Введите элементы второго списка через пробел: ').split() ] print(f"Список 1: {str(list1)}") print(f"Список 2: {str(list2)}") if collections.Counter(list1) == collections.Counter(list2): print("Множества элементов совпадают") else: print("Множества не совпадают")
def freq_numb(): """The frequency of using digits in a range of numbers. Input arguments: a, b are integer. Output: dictionary with digits and their number in the text. """ while True: try: a = int(m.text("Введите первое число: ")) b = int(m.text("Введите последнее число: ")) symbols = {} string = "".join(map(str, range(a, b))) for i in string: if i in symbols: symbols[i] += 1 else: symbols[i] = 1 print("Количество цифр в диапазоне:\n " + str(symbols)) break except ValueError: print("Вы ввели не число. Попробуйте снова: ")
def freq_symb(): """Determine the frequency of using all characters in the text. Input Arguments: string. Output: dictionary with symbols and their number in the text. """ string = (m.text("Введите строку: ")) symbols = {} for i in string: if i in symbols: symbols[i] += 1 else: symbols[i] = 1 print("Количество символов в строке:\n " + str(symbols))
def symbols(): """Counting the frequency of characters in the text. Input arguments: text, must be string. Output: dictionary of symbols. """ string = (m.text("Введите строку: ")) symbols = {} for i in string: if i in symbols: symbols[i] += 1 else: symbols[i] = 1 print("Количество символов в строке:\n " + str(symbols))
def light(): """Accepts a color as input, implements the work of a traffic light Input Argument: color, must be string Output: Returns a permitted action """ color = m.text("Введите цвет: ") if color == 'Зеленый': print("Движение разрешено") elif color == 'Красный': print("Движение запрещено") elif color == 'Желтый': print("Дождитесь смены сигнала") else: print ("Такого сигнала нет")
def light_inf(): """Accepts a color as input, implements the work of a traffic light Input Argument: color, must be string Output: Returns a permitted action Exit condition: string "Выход" """ while 5 < 6: color = m.text("Введите цвет: ") if color == ('Выход'): break else: if color == 'Зеленый': print("Движение разрешено") elif color == 'Красный': print("Движение запрещено") elif color == 'Желтый': print("Дождитесь смены сигнала") else: print ("Такого сигнала нет")
def brackets(): """Checking for correct parentheses in text. Input arguments: text with brackets, must be string. Output: correctness message. """ text = [str(i) for i in m.text('Введите текст со скобками: ')] bkt_open = ["[", "{", "(", "<"] bkt_close = ["]", "}", ")", ">"] stack = [] for i in text: if i in bkt_open: stack.append(i) elif i in bkt_close: tmp = bkt_close.index(i) if ((len(stack) > 0) and (bkt_open[tmp] == stack[len(stack) - 1])): stack.pop() else: print("Скобки расставлены некорректно") if len(stack) == 0: print("Скобки расставлены корректно")
else: try: oprtn = (step[0]) y = float(step[1:]) except ValueError: print("""Нерпавильный ввод. Введите 'операция''операнд'""") except ZeroDivisionError: print("Деление на ноль") else: print(f"""Результат: {x} {oprtn} {y} = {calc(x, y, oprtn)} Продолжаем считать? """) x = calc(x, y, oprtn) while True: next_step = m.text(""" Выберите задачу: Факториал: 1 Калькулятор: 2 Выход: Enter """) if not next_step: print("Всего хорошего...") break else: m.choose_task(next_step, fact, calculate)
""" while 5 < 6: color = m.text("Введите цвет: ") if color == ('Выход'): break else: if color == 'Зеленый': print("Движение разрешено") elif color == 'Красный': print("Движение запрещено") elif color == 'Желтый': print("Дождитесь смены сигнала") else: print ("Такого сигнала нет") """Task selection. Inputs: 1, 2 or Enter""" while True: next_step = m.text( """ Выберите задачу: Светофор: 1 Светофор в бесконечном цикле: 2 Выход: Enter """ ) if not next_step: print("Увидимся...") break else: m.choose_task(next_step, light, light_inf)
import mymodule mymodule.greeting("Jonathan") mymodule.text("Vince") mymodule.print(mul(3)) mymodule.print(div(3)) mymodule.print(int_Floor(7, 8)) mymodule.print(int_Exponent(7, 8)) mymodule.print(int_Modulo(7, 8)) mymodule.print(int_MDAS(7, 8, 9)) mymodule.print(int_PEMDAS(7, 8, 9)) mymodule.print(float_convert(3))
"""The script performs simple arithmetic calculations Input arguments: operation name, strings: 'Простое число', 'НОД' or 'НОК' Args n, a, b, x, y are integers """ import math import mymodule as m while True: task = m.text("Введите задание: ") if task.isdigit(): print(f"Неправильный ввод, попробуйте снова") else: if task == ('Выход'): break else: if task == 'Простое число': # Простое число n = int(m.text("Введите число: ")) k = 0 for i in range(2, n): if (n % i == 0): k = k + 1 if (k > 1): print(f"Число {n} не является простым") else: print(f"Число {n} простое") elif task == 'НОД':
""" script for finding the roots of a quadratic equation. Input arguments: a, b, c must be integer, real or complex """ import cmath import math import mymodule as m while True: try: a = float(m.text("Введите a = ")) b = float(m.text("Введите b = ")) c = float(m.text("Введите c = ")) if a == 0: if b == 0: print("Такие коэфициенты недопустимы") else: x = -c / b print("x = {x}") else: D = b**2 - (4 * a * c) print(f"Дискриминант = {D}") if D < 0: x1 = (-b + cmath.sqrt(D)) / (2 * a) x2 = (-b - cmath.sqrt(D)) / (2 * a)
for i in range(time): dep = (sum + (sum * percent) / 100) return dep while True: try: sum = int(m.text("Введите размер взноса: ")) percent = int(m.text("Введите банковский процент: ")) time = int(m.text("Введите количество месяцев: ")) except: print('Еще раз') continue else: print(f"""Предполагаемая сумма денег на вкладе: {deposit(sum, percent, time)}""") break while True: next_step = m.text(""" Выберите задачу: Факториал: 1 Копилка: 2 Выход: Enter """) if not next_step: print("Всего хорошего...") break else: m.choose_task(next_step, fact, bank)
Output: word count. """ str = (m.text("Введите текст: ")) n = len(str.split()) print(f"Количество слов в тексте: {n}") def sentences(): """Counting the number of sentences in the text. Input arguments: text, must be string. Output: sentences count. """ text = (m.text("Введите текст: ")) a = text.count('. ') + text.count('! ') + text.count('? ') + 1 print(f"Количество предложений в тексте: {a}") while True: next_step = m.text(""" Выберите задачу: Частота вхождений символов в текст: 1 Количество слов в тексте: 2 Количество предложений в тексте: 3 Выход: Enter """) if not next_step: print("Всего хорошего...") break else: m.choose_task_3(next_step, symbols, words, sentences)
""" list1 = [ str(i) for i in m.text( 'Введите элементы первого списка через пробел: ').split() ] list2 = [ str(i) for i in m.text( 'Введите элементы второго списка через пробел: ').split() ] print(f"Список 1: {str(list1)}") print(f"Список 2: {str(list2)}") if collections.Counter(list1) == collections.Counter(list2): print("Множества элементов совпадают") else: print("Множества не совпадают") while True: next_step = m.text(""" Выберите задачу: Сортировка пузырьком: 1 Сравнение множеств списков: 2 Выход: Enter """) if not next_step: print("Увидимся...") break else: m.choose_task(next_step, sort, coinc)
import mymodule as m def XOR(input_str, encryption_key): """Exclusive disjunction Input arguments: message and key, must be string Output: encrypted and decrypted strings """ encrypted = "" length = len(encryption_key) for i in range(0, len(input_str)): letter = input_str[i] key = encryption_key[i % length] encrypted += chr(ord(letter) ^ ord(key)) return encrypted input_str = (m.text("Введите шифр: ")) input_key = (m.text("Введите ключ: ")) print(f"Введенная строка: {input_str}") encr_strg = XOR(input_str, input_key) print(f"Зашифрованная строка: {encr_strg}") print(f"Расшифрованная строка: {XOR(encr_strg, input_key)}")
def fizz_buzz(): """FizzBuzz 0 to 100. Prints numbers or words. """ for i in range(0, 101): if i % 15 == 0: print(f"FizzBuzz") elif i % 3 == 0: print(f"Fizz") elif i % 5 == 0: print(f"Buzz") else: print(i) while True: next_step = m.text(""" Выберите задачу: Частота символов: 1 Частота цифр: 2 FizzBuzz: 3 Выход: Enter """) if not next_step: print("Увидимся...") break else: m.choose_task_3(next_step, freq_symb, freq_numb, fizz_buzz)
L2.append(S.pop()) return L2 def CALC(L): """Calculations.""" St = [] for i in L: if i == '+': St.append(int(St.pop()) + int(St.pop())) elif i == '-': St.append(-int(St.pop()) + int(St.pop())) elif i == '*': St.append(int(St.pop()) * int(St.pop())) elif i == '/': a = int(St.pop()) b = float(St.pop()) St.append(b / a) else: St.append(i) return St[0] s = m.text("Введите пример: ") L = LIST(s) L = POL(L) print(f"Ответ: {int(CALC(L))}")
bkt_open = ["[", "{", "(", "<"] bkt_close = ["]", "}", ")", ">"] stack = [] for i in text: if i in bkt_open: stack.append(i) elif i in bkt_close: tmp = bkt_close.index(i) if ((len(stack) > 0) and (bkt_open[tmp] == stack[len(stack) - 1])): stack.pop() else: print("Скобки расставлены некорректно") if len(stack) == 0: print("Скобки расставлены корректно") while True: next_step = m.text(""" Выберите задачу: Удаление встречающихся элементов: 1 Проверка скобок: 2 Выход: Enter """) if not next_step: print("Увидимся...") break else: m.choose_task(next_step, del_same, brackets)
Input arguments: n, must be an integer. Output: factorial of number n. """ n = int(m.text('Введите натуральное число для вычисления факториала: ')) print((lambda a: math.factorial(a))(n)) def freq(): """Counting the frequency of characters in the text. Input arguments: text, must be string. Output: dictionary of symbols. """ text = (m.text("Введите строку: ")) print((lambda res: Counter(res))(text)) while True: next_step = m.text(""" Выберите задачу: Факториал: 1 Частота символов: 2 Выход: Enter """) if not next_step: print("Увидимся...") break else: m.choose_task(next_step, fact, freq)
def calculate(): """Сalculator for basic operations. Input arguments: x, first number, must be float, step - operation and operand without space, sting. Output: the calculation result. """ print(""" Возможные операции: + сложение - вычитание * умножение / деление ^ возведение в степень % получение остатка от деления """) def calc(a, b, operation): """Receives two operands and an operation, calls an operation on the operands""" def add(a1, b1): """Returns the result of adding operands""" return a1 + b1 def remove(a1, b1): """Returns the result of subtraction operands""" return a1 - b1 def multiply(a1, b1): """Returns the result of multiplication operands""" return a1 * b1 def divide(a1, b1): """Returns the result of division operands""" return (a1) / (b1) def exp(a1, b1): """Returns the result of exponentiation operands""" return a1**b1 def res(a1, b1): """Returns the remainder of the division operands""" return a1 % b1 selector = { "+": add, "-": remove, "*": multiply, "/": divide, "^": exp, "%": res } return selector[operation](a, b) try: x = float(m.text('Введите первое число: ')) except ValueError: print("Вы ввели не число. Попробуйте еще раз ") else: while True: step = (m.text('(Enter - выход) \ Введите операцию и операнд: ')) if not step: print("Всего хорошего...") break else: try: oprtn = (step[0]) y = float(step[1:]) except ValueError: print("""Нерпавильный ввод. Введите 'операция''операнд'""") except ZeroDivisionError: print("Деление на ноль") else: print(f"""Результат: {x} {oprtn} {y} = {calc(x, y, oprtn)} Продолжаем считать? """) x = calc(x, y, oprtn)