diff --git a/.vscode/.ropeproject/config.py b/.vscode/.ropeproject/config.py new file mode 100644 index 0000000..dee2d1a --- /dev/null +++ b/.vscode/.ropeproject/config.py @@ -0,0 +1,114 @@ +# The default ``config.py`` +# flake8: noqa + + +def set_prefs(prefs): + """This function is called before opening the project""" + + # Specify which files and folders to ignore in the project. + # Changes to ignored resources are not added to the history and + # VCSs. Also they are not returned in `Project.get_files()`. + # Note that ``?`` and ``*`` match all characters but slashes. + # '*.pyc': matches 'test.pyc' and 'pkg/test.pyc' + # 'mod*.pyc': matches 'test/mod1.pyc' but not 'mod/1.pyc' + # '.svn': matches 'pkg/.svn' and all of its children + # 'build/*.o': matches 'build/lib.o' but not 'build/sub/lib.o' + # 'build//*.o': matches 'build/lib.o' and 'build/sub/lib.o' + prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject', + '.hg', '.svn', '_svn', '.git', '.tox'] + + # Specifies which files should be considered python files. It is + # useful when you have scripts inside your project. Only files + # ending with ``.py`` are considered to be python files by + # default. + # prefs['python_files'] = ['*.py'] + + # Custom source folders: By default rope searches the project + # for finding source folders (folders that should be searched + # for finding modules). You can add paths to that list. Note + # that rope guesses project source folders correctly most of the + # time; use this if you have any problems. + # The folders should be relative to project root and use '/' for + # separating folders regardless of the platform rope is running on. + # 'src/my_source_folder' for instance. + # prefs.add('source_folders', 'src') + + # You can extend python path for looking up modules + # prefs.add('python_path', '~/python/') + + # Should rope save object information or not. + prefs['save_objectdb'] = True + prefs['compress_objectdb'] = False + + # If `True`, rope analyzes each module when it is being saved. + prefs['automatic_soa'] = True + # The depth of calls to follow in static object analysis + prefs['soa_followed_calls'] = 0 + + # If `False` when running modules or unit tests "dynamic object + # analysis" is turned off. This makes them much faster. + prefs['perform_doa'] = True + + # Rope can check the validity of its object DB when running. + prefs['validate_objectdb'] = True + + # How many undos to hold? + prefs['max_history_items'] = 32 + + # Shows whether to save history across sessions. + prefs['save_history'] = True + prefs['compress_history'] = False + + # Set the number spaces used for indenting. According to + # :PEP:`8`, it is best to use 4 spaces. Since most of rope's + # unit-tests use 4 spaces it is more reliable, too. + prefs['indent_size'] = 4 + + # Builtin and c-extension modules that are allowed to be imported + # and inspected by rope. + prefs['extension_modules'] = [] + + # Add all standard c-extensions to extension_modules list. + prefs['import_dynload_stdmods'] = True + + # If `True` modules with syntax errors are considered to be empty. + # The default value is `False`; When `False` syntax errors raise + # `rope.base.exceptions.ModuleSyntaxError` exception. + prefs['ignore_syntax_errors'] = False + + # If `True`, rope ignores unresolvable imports. Otherwise, they + # appear in the importing namespace. + prefs['ignore_bad_imports'] = False + + # If `True`, rope will insert new module imports as + # `from import ` by default. + prefs['prefer_module_from_imports'] = False + + # If `True`, rope will transform a comma list of imports into + # multiple separate import statements when organizing + # imports. + prefs['split_imports'] = False + + # If `True`, rope will remove all top-level import statements and + # reinsert them at the top of the module when making changes. + prefs['pull_imports_to_top'] = True + + # If `True`, rope will sort imports alphabetically by module name instead + # of alphabetically by import statement, with from imports after normal + # imports. + prefs['sort_imports_alphabetically'] = False + + # Location of implementation of + # rope.base.oi.type_hinting.interfaces.ITypeHintingFactory In general + # case, you don't have to change this value, unless you're an rope expert. + # Change this value to inject you own implementations of interfaces + # listed in module rope.base.oi.type_hinting.providers.interfaces + # For example, you can add you own providers for Django Models, or disable + # the search type-hinting in a class hierarchy, etc. + prefs['type_hinting_factory'] = ( + 'rope.base.oi.type_hinting.factory.default_type_hinting_factory') + + +def project_opened(project): + """This function is called after opening the project""" + # Do whatever you like here! diff --git a/class_work/lection_3.py b/class_work/lection_3.py new file mode 100644 index 0000000..003d669 --- /dev/null +++ b/class_work/lection_3.py @@ -0,0 +1,36 @@ +''' DRY ''' +''' +''' + +def is_some(number: int, count: int) -> bool: + '''Функция возвращает результат проверки является ли число n разрядным + :number: int число + :count: int количество разрядов + :return: bool: + ''' + return 1 <= (number // 10 ** (count -1)) < 10 + +a: bool = is_some(123, 3) #аннотация +b: float = is_some(123, 4) #аннотация не влияет на выполнение +c = is_some(12, 5) +d = is_some(124523446, 6) + +print(a, b, c, d) +print(any((a, b, c, d))) +print(all((a, b, c, d))) +# + +def some(number): + # как использовать Степень делимого для определения условия ? + ''' + >>> some(34235253) + NO + >>> some(53) + NO + >>> some(353) + YES + ''' + answer = ('NO','YES') + print(answer[1 <= (number // 100) < 10]) + +some(353) \ No newline at end of file diff --git a/class_work/lection_3_2.py b/class_work/lection_3_2.py new file mode 100644 index 0000000..cbda742 --- /dev/null +++ b/class_work/lection_3_2.py @@ -0,0 +1,103 @@ + +def is_some(number: int, count: int) -> bool: + '''Функция возвращает результат проверки является ли число n разрядным + :number: int число + :count: int количество разрядов + :return: bool: + ''' + return 1 <= (number // 10 ** (count -1)) < 10 + +b = {24323, 5} + +print(is_some(*b)) + +a = { + 'count': 5, + 'number': 234, +} + +print(is_some(**a)) + +print(is_some(number=5,count=235)) +print(is_some(count=2256,number=5)) + +''' +zip +map +''' + +def dd_map(func, iter_obj): + '''Map this shit''' + for item in iter_obj: + yield func(item) + +a = dd_map(str, [1, 2, 3, 4, 5]) + +print(a) + +def dd_sum(*stuff): + result = 0 + for n in stuff: + result += n + return result + +print(dd_sum(1, 2, 3, 4,5)) + +def dd_sum_2(*stuff, factor=1): + print('factor ', factor) + result = 0 + for n in stuff: + result += n + return result * factor + +print(dd_sum_2(1, 2, 3, 4, 5, factor=5)) + +def dd_sum_3(*stuff, **kwargs): + print('kwargs ', kwargs) + print(stuff) + result = 0 + for n in stuff: + result += n + return result + +print(dd_sum_3(1, 2, 3, 4, 5, factor=562)) + +a = 1 +b = 10 + +c = [] + +for n in range(a, b+1): + c.append(n**2) +print(c) + +d = [n**2 for n in range(a, b+1)] +print(d) + +list_a = [1, 2, 3, 4, 5] +list_b = [100, 200, 300, 400, 500] + +list_combinations = [(n_a, n_b) for n_a in list_a for n_b in list_b] + +print(list_combinations) +print(list_combinations[2]) + +#result = {1: 1 ** 2, 2: 2**2} +list_result = {n: n ** 2 for n in list_a} +print(list_result) + +list_result = {n: n ** 2 for n in list_a if n & 1} +print(list_result) + +list_result = {n: n ** 2 for n in list_a if not n & 1} +print(list_result) + +list_result = tuple( n ** 2 for n in list_a if n & 1) +print(list_result) + +list_result = tuple( n ** 2 for n in list_a if not n & 1) +print(list_result) + +'''result = [] +for n_a in list_a: + for n_b in list_b:''' diff --git a/les3_task1.py b/les3_task1.py new file mode 100644 index 0000000..5983ace --- /dev/null +++ b/les3_task1.py @@ -0,0 +1,25 @@ +'''1) Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.''' + +def divider(a: int, b:int): # -> int: + try: + result = a // b + except ZeroDivisionError: + print(f' Ошибка деления на 0 ') + result = str('Nan') + return result + +def user_input(): + while True: + user_input = input('iput int:\n>') + if user_input.isdigit(): + user_input = int(user_input) + return user_input + elif user_input == 'x': + print('enter canceled\n 0 set by default') + return 0 + else: + print('Not a number, type "x" for cancel:') + +output_divider = divider(user_input(), user_input()) + +input(f'Результат = {output_divider}\n>ok') diff --git a/les3_task2.py b/les3_task2.py new file mode 100644 index 0000000..db124cf --- /dev/null +++ b/les3_task2.py @@ -0,0 +1,7 @@ +'''2) Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя: имя, фамилия, год рождения, город проживания, email, телефон. Функция должна принимать параметры как именованные аргументы. Реализовать вывод данных о пользователе одной строкой.''' + +def input_to_string(a, b, c, d, e, f): + print(f'Пользователь: {a} {b} {c}г.р., г.{d}, email: {e}, телефон: {f}') + +input_to_string(e = 'pirog.v@ya.ru', a = 'Василий', b = 'Пирожков', c = '1984', d = 'Бобруйск', f = '88005678432') + diff --git a/les3_task3.py b/les3_task3.py new file mode 100644 index 0000000..c33097c --- /dev/null +++ b/les3_task3.py @@ -0,0 +1,8 @@ +'''3) Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов.''' + +def my_func(a,b,c): + my_list = sorted([a, b, c]) + #print(sum(my_list[-2:])) + return sum(my_list[-2:]) + +print(my_func(5, 1 ,2)) diff --git a/les3_task4.py b/les3_task4.py new file mode 100644 index 0000000..5f3fb7a --- /dev/null +++ b/les3_task4.py @@ -0,0 +1,33 @@ +'''4) Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). При решении задания необходимо обойтись без встроенной функции возведения числа в степень. +Подсказка: попробуйте решить задачу двумя способами. Первый — возведение в степень с помощью оператора **. Второй — более сложная реализация без оператора **, предусматривающая использование цикла.''' + +def my_func(x, y): + outout = x ** y + return outout + +print(my_func(2, -2)) + +def fastExp(b, n): + def even(n): #проверка четности + if n%2 == 0: + return 1 + return 0 + if n == 0: + return 1 + if even(n): + return fastExp(b, n/2)**2 + return b*fastExp(b, n-1) + +print(fastExp(2, 0)) + +def negative_exp(x, y): + result = 1 + for el in range(abs(y)): + result *= x + if y >= 0: + return result + else: + return 1 / result + +print(negative_exp(2, -2)) + diff --git a/les3_task5.py b/les3_task5.py new file mode 100644 index 0000000..c471759 --- /dev/null +++ b/les3_task5.py @@ -0,0 +1,34 @@ +'''5) Программа запрашивает у пользователя строку чисел, разделенных пробелом. При нажатии Enter должна выводиться сумма чисел. Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter. Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме. Но если вместо числа вводится специальный символ, выполнение программы завершается. Если специальный символ введен после нескольких чисел, то вначале нужно добавить сумму этих чисел к полученной ранее сумме и после этого завершить программу.''' + +import re # regular expressions module + +def numbers_from_string(user_string = ""): + '''Returns numbers found in string to list + user_string: str''' + out = re.findall(r'\d+', user_string) + return out + +def summ_func(num_list): + '''Return summ of elements in list + num_list: list''' + out = 0 + for el in num_list: + out += int(el) + return out + +def exit_flag_fc(user_string, spc_char = 'x'): + '''Returns -1 if spc_char not found in string , or index of result''' + flag = user_string.find(spc_char) + return flag + +exit_flag = -1 +final_summ = 0 + +while exit_flag == -1: + user_string = input("enter nums useing space, and/or 'x' to exit)") + tmp_list = numbers_from_string(user_string) + final_summ = final_summ + summ_func(tmp_list) + print(f'final_summ {final_summ}') + exit_flag = exit_flag_fc(user_string) + +input('ok _>') diff --git a/les3_task6.py b/les3_task6.py new file mode 100644 index 0000000..9bccc62 --- /dev/null +++ b/les3_task6.py @@ -0,0 +1,32 @@ +'''6) Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text. +Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом. Каждое слово состоит из латинских букв в нижнем регистре. Сделать вывод исходной строки, но каждое слово должно начинаться с заглавной буквы. Необходимо использовать написанную ранее функцию int_func().''' + +def int_func(word): + return word.title() + +def mass_titles(words_string): + tmp_list = words_string.split() + out_str = '' + for el in tmp_list: + out_str = (f'{out_str} {int_func(el)}') + return out_str + + +print(mass_titles('sdjfh sdkjhfkj dskjhf eqwrio qwp')) + + +def int_func_exampl(string: str): + return ''.join((string[0].upper(), string[1:])) if string else string + +def user_temp(string: str): + return ' '.join(map(int_func_exampl, string.split(' '))) + + +assert int_func_exampl('рокетлаунчер') == 'Рокетлаунчер', "int_func('рокетлаунчер')" +assert int_func_exampl('кваддамейдж') == 'Кваддамейдж', "int_func('кваддамейдж')" +assert int_func_exampl('') == '', "int_func('')" + +print(user_temp('бабка переходит дорогу')) +#assert user_temp('бабка переходит дорогу') == 'Бабка Переходит Дорогу', "user_temp('бабка переходит дорогу')" + +#input('ok >') diff --git a/lesson_3/test.txt.3.txt b/lesson_3/test.txt.3.txt deleted file mode 100644 index e69de29..0000000 diff --git a/test.txt.3.txt b/test.txt.3.txt deleted file mode 100644 index e69de29..0000000