Skip to content

lesson_3 #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
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions .vscode/.ropeproject/config.py
Original file line number Diff line number Diff line change
@@ -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 <package> import <module>` 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!
36 changes: 36 additions & 0 deletions class_work/lection_3.py
Original file line number Diff line number Diff line change
@@ -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)
103 changes: 103 additions & 0 deletions class_work/lection_3_2.py
Original file line number Diff line number Diff line change
@@ -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:'''
25 changes: 25 additions & 0 deletions les3_task1.py
Original file line number Diff line number Diff line change
@@ -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')
7 changes: 7 additions & 0 deletions les3_task2.py
Original file line number Diff line number Diff line change
@@ -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 = '[email protected]', a = 'Василий', b = 'Пирожков', c = '1984', d = 'Бобруйск', f = '88005678432')

8 changes: 8 additions & 0 deletions les3_task3.py
Original file line number Diff line number Diff line change
@@ -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))
33 changes: 33 additions & 0 deletions les3_task4.py
Original file line number Diff line number Diff line change
@@ -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))

34 changes: 34 additions & 0 deletions les3_task5.py
Original file line number Diff line number Diff line change
@@ -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 _>')
Loading