From af3a7fef5f8e77b26436174ba9912c4d676eeb54 Mon Sep 17 00:00:00 2001 From: BerezhkovDA Date: Fri, 26 Sep 2025 00:14:37 +0300 Subject: [PATCH] =?UTF-8?q?=D0=BE=D1=82=D1=87=D0=B5=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TEMA2/report.md | 373 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 373 insertions(+) create mode 100644 TEMA2/report.md diff --git a/TEMA2/report.md b/TEMA2/report.md new file mode 100644 index 0000000..889dfac --- /dev/null +++ b/TEMA2/report.md @@ -0,0 +1,373 @@ +# Отчет по теме 2 +Бережков Дмитрий, А-01-23 +## 1. Изучение простых объектов +```py +>>> import os +>>> os.chdir('C:\\MPEI\\PO_ASY\\BerezhkovGit\\python-labs\\Tema2') +>>> f1=16; f2=3 +>>> f1,f2 +(16, 3) +>>> f1;f2 +16 +3 +>>> dir() +>>> dir(f1) +['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'is_integer', 'numerator', 'real', 'to_bytes'] +['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'f1', 'f2', 'os'] +>>> type(f2) + +>>> del(f1,f2) +>>> dir() +['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'os'] +``` +## 2. Изучение правил именования объектов +```py +>>> gg1=1.6 +>>> hh1='Строка' +>>> 73sr=3 +SyntaxError: invalid decimal literal +>>> and=7 +SyntaxError: invalid syntax +``` +## 3. Список ключевых слов +```py +>>> import keyword +>>> keyword.kwlist +['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] +>>> w=keyword.kwlist +>>> w +['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] +``` +## 4. Список встроенных идентификаторов +```py +>>> import builtins +>>> dir(builtins) +['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BaseExceptionGroup', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'ExceptionGroup', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'PythonFinalizationError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '_IncompleteInputError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip'] +``` +## 5. Встроенные идентификаторы и встроенные функции +```py +>>> import builtins +>>> dir(builtins) +['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BaseExceptionGroup', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'ExceptionGroup', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'PythonFinalizationError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '_IncompleteInputError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip'] +``` +Базовые функции: +```py +>>> abs(-10) +10 +>>> len([1,2,3]) +3 +>>> max([1,2,3,4,5]) +5 +>>> min([1,2,3,4,5]) +1 +>>> pow(2,5) +32 +>>> pi=3.14159 +>>> round(pi,3) +3.142 +>>> unsorted_list = [3, 1, 4, 1, 5, 9, 2, 6] +>>> sorted_list = sorted(unsorted_list) +>>> print(sorted_list) +[1, 1, 2, 3, 4, 5, 6, 9] +>>>num=[1,2,3,4,5] +>>>print(sum(num)) +15 +>>>names = ["Oreshki", "Big", "Bob"] +>>> val=[25,25,25] +>>> zipp=zip(names,val) +>>> print(list(zipp)) +[('Oreshki', 25), ('Big', 25), ('Bob', 25)] +``` +## 6. Учёт регистра +```py +>>> Gg1=45 +>>> gg1 +1.6 +>>> Gg1 +45 +``` +## 7. Изучение простых базовых типов объектов: +7.1 Логический тип: +```py +>>> bb1=True; bb2=False +>>> bb1;bb2 +True +False +>>> type(bb1) + +``` +7.2 Другие простые типы: +```py +>>> ii1=-1234567890 +>>> ff1=-8.9876e-12 +>>> dv1=0b1101010 +>>> vsm1=0o52765 +>>> shest1=0x7109af6 +>>> cc1=2-3j +>>> a=3.67;b=-0.45 +>>> cc2=complex(a,b) +>>> type(ii1) + +>>> type(ff1) + +>>> type(dv1) + +>>> type(vsm1) + +>>> type(shest1) + +>>> type(cc1) + +>>> type(cc2) + +``` +7.3 Строка символов: +```py +>>> ss1='Это - строка символов' +>>> ss1;type(ss1) +'Это - строка символов' + +>>> ss1a="Это - \" строка символов \", \n \t выводимая на двух строках" +>>> print(ss1a) +Это - " строка символов ", + выводимая на двух строках +>>> ss1b= 'Меня зовут: \n Бережков Д. А.' +>>> print(ss1b) +Меня зовут: + Бережков Д. А. +>>> mnogo="Нетрудно заметить , что в результате операции над числами разных типов получается число, имеющее болле сложный тип из тех, которые учавствуют в операции" +>>> print(mnogo) +Нетрудно заметить , что в результате операции над числами разных типов получается число, имеющее болле сложный тип из тех, которые учавствуют в операции +>>> ss1[0] +'Э' +>>> ss1[8] +'р' +>>> ss1[-2] +'о' +>>> ss1[6:9] +'стр' +>>> ss1[13:] +'символов' +>>> ss1[:13] +'Это - строка ' +>>>ss1[5:-8] +' строка ' +>>> ss1[3:17:2] +' тоасм' +>>> ss1[17:3:-2] +'омсаот ' +``` +Так как индекс -4 и 17 равны в строке, тогда с помощью этой строки кода получим то же самое: +```py +>>> ss1[-4:3:-2] +'омсаот ' +``` +Строка неизменяемый объект: +```py +>>> ss1[4]='=' # Будет диагностика! +Traceback (most recent call last): + File "", line 1, in +>>> ss1[4]='=' # Будет диагностика! +TypeError: 'str' object does not support item assignment +``` +```py +>>> ss1=ss1[:4]+'='+ss1[5:] +>>> ss1 +'Это = строка символов' +>>> ss1b=ss1b[:0]+'='+ss1b[10:] +>>> ss1b +'=: \n Бережков Д. А.' +``` +Создание еще несколько объектов разных типов данных: +```py +>>> a = -8; a; type(a) +-8 + +>>> a = 1.1; a; type(a) +1.1 + +>>> a = True; a; type(a) +True + +>>> a = 8 - 9j; a; type(a) +(8-9j) + +>>> a = complex(6,4); a; type(a) +(6+4j) + +>>> a = 'String'; a; type(a) +'String' + +``` +## 8. Более сложные типы объектов +8.1 Списки: +```py +>>> spis1=[111,'Spisok',5-9j] +>>> stup=[0,0,1,1,1,1,1,1,1] +>>> spis=[1,2,3,4,5,6,7,8,9,10] +>>> spis1[-1] +(5-9j) +>>> stup[-8::2] +[0, 1, 1, 1] +``` +В список stup вошло 4 элемента с индексами из исходного списка: [-8] ([1]), [-6] ([3]), [-4] ([5]) и [-2] ([7]) +```py +>>> spis1[1]='Список' +>>> spis1 +[111, 'Список', (5-9j)] +>>> len(spis1) +3 +``` +```py +>>> help(spis1.append) +Help on built-in function append: + +append(object, /) method of builtins.list instance + Append object to the end of the list. +>>> spis1.append('New item') +>>> spis1 +[111, 'Список', (5-9j), 'New item'] +>>> spis1.pop(1) +'Список' +>>> spis1 +[111, (5-9j), 'New item'] +``` +Также могут использоваться методы insert, remove, extend, clear, sort, reverse, copy, count, index: +```py +>>> spis1.insert(1, 'string') +>>> spis1 +[111, 'string', (5-9j), 'New item'] + +>>> spis1.remove(111) +>>> spis1 +['string', (5-9j), 'New item'] + +>>> new_list = [1, 2, 3] +>>> spis1.extend(new_list) +>>> spis1 +['string', (5-9j), 'New item', 1, 2, 3] + +>>> new_list.clear() +>>> new_list +[] + +>>> new_list = [3, 1, 2] +>>> new_list.sort() +>>> new_list +[1, 2, 3] + +>>> new_list.reverse() +>>> new_list +[3, 2, 1] + +>>> new_list2 = new_list.copy() +>>> new_list2 +[1, 2, 3] + +>>> new_list = [1, 2, 2, 2, 3, 3] +>>> new_list.count(2) +3 + +>>> new_list = ['one', 'two', 'three'] +>>> new_list.index('three') +2 +``` +```py +>>> spis2=[spis1,[4,5,6,7]] +>>> spis2[0][1] +(5-9j) +>>> spis2[0][1]=78 +>>> spis1 # в spis2 сохраняется ссылка на объект spis1, а не копия списка (spis2[0] и spis1 — это один и тот же список в памяти) +['string', 78, 'New item', 1, 2, 3] +``` +```py +>>> my_list = [12, 'str', True, [1, 2, 3]] +>>> my_list +[12, 'str', True, [1, 2, 3]] +``` +8.2 Кортежи +```py +>>> kort1=(222,'Kortezh',77+8j) +>>> kort1= kort1+(1,2) +>>> kort1= kort1+(ss1b,) +>>> kort1=(222,'Kortezh',77+8j) +>>> kort1 +(222, 'Kortezh', (77+8j)) +>>> kort1= kort1+(1,2) +>>> kort1 +(222, 'Kortezh', (77+8j), 1, 2) +>>> kort1= kort1+(ss1b,) +>>> kort1 +(222, 'Kortezh', (77+8j), 1, 2, '=: \n Бережков Д. А.') +>>> kort2=kort1[:2]+kort1[3:] +>>> kort2 +(222, 'Kortezh', 1, 2, '=: \n Бережков Д. А.') +>>> kort1.index(2) +4 +>>> kort1.count(222) +1 +>>> kort1[2]=90 +Traceback (most recent call last): + File "", line 1, in +>>> kort1[2]=90 +TypeError: 'tuple' object does not support item assignment +>>> my_kort = (12, 'str', [1, 2, 3], (222, 'str')) +>>> my_kort +(12, 'str', [1, 2, 3], (222, 'str')) +``` +8.3 Словари +```py +>>> dic1={'Saratov':145, 'Orel':56, 'Vologda':45} +>>> dic1['Orel'] +56 +>>> dic1['Pskov']=78 +>>> dic1 +{'Saratov': 145, 'Orel': 56, 'Vologda': 45, 'Pskov': 78} +>>> sorted(dic1.keys()) +['Orel', 'Pskov', 'Saratov', 'Vologda'] +>>> sorted(dic1.values()) +[45, 56, 78, 145] +>>>dic2={1:'mean',2:'standart deviation',3:'correlation'} +>>> dic3={'statistics':dic2,'POAS':['base','elementary','programming']} +>>> dic3['statistics'][2] +'standart deviation' +>>> dic4=dict([(1,['A','B','C']),(2,[4,5]),('Q','Prim'),('Stroka',ss1b)]) +>>> dic5=dict(zip(['A','B','C','Stroka'],[16,-3,9,ss1b])) +>>> dic4 +{1: ['A', 'B', 'C'], 2: [4, 5], 'Q': 'Prim', 'Stroka': '=: \n Бережков Д. А.'} +>>> dic5 +{'A': 16, 'B': -3, 'C': 9, 'Stroka': '=: \n Бережков Д. А.'} +>>> t = ("a", "b", "c", "d", "e", "f", "g") +>>> l = [1, 2, 3, 4, 5] +>>> d = dict(zip(t, l)) +>>> d # Элементов в получившимся словаре - 5, т.к. zip() работает до конца самого короткого объекта +{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} +``` +```py +>>> AVTI={'Курс I':[22,23,17,24,30,29,28,25,23,0,4,31,30,33,18,12,27],'Курс II':[18,16,12,15,29,18,21,23,13,0,4,20,31,26,16,], 'Курс III':[17,12,0,6,17,15,19,19,0,0,5,17,22,18,12], 'Курс IV':[27,16,0,13,17,15,19,20,0,0,2,15,18,16,17]} +>>> AVTI['Курс III'][5] +15 +``` +8.4 Множества +```py +>>> mnoz1={'двигатель','датчик','линия связи','датчик','микропроцессор','двигатель'} +>>> mnoz1 +{'двигатель', 'датчик', 'микропроцессор', 'линия связи'} +>>> len(mnoz1) +4 +'датчик' in mnoz1 +True +>>> mnoz1.add('реле') +>>> mnoz1 +{'двигатель', 'датчик', 'линия связи', 'реле', 'микропроцессор'} +>>> mnoz1.remove('линия связи') +>>> mnoz1 +{'двигатель', 'датчик', 'реле', 'микропроцессор'} +>>> s = {1, "hello", True, 3.14, (2, 5)} +>>> s.add("Python") +>>> s +{1, 3.14, 'Python', (2, 5), 'hello'} +>>> s.remove(3.14) +>>> s +{1, 'Python', (2, 5), 'hello'} +``` \ No newline at end of file