# Протокол ПО АС по теме 2 Выполнил: Тимошенко А.А. Проверил : Козлюк Д. А. # Пункт 1 Рабочая среда настроена на нахождение в нужной директории: ``` import os os.chdir("C:/Users/mapon/OneDrive/Рабочий стол/ПО АС/ТЕМА2") ``` # Пункт 2 Создадим два простых объекта - переменные f1 и f2. Это можно сделать в одну строку: ``` f1=16;f2=3 ``` Можно вывести эти переменные через запятую. Тогда они будут отображены как кортеж: ``` f1, f2 (16, 3) ``` Или через точку с запятой. тогда друг за другом: ``` f1;f2 16 3 ``` Функция dir() покажет, какие объекты находятся в текущем рабочем пространстве: ``` dir() ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'f1', 'f2', 'os'] ``` Еще эта функция может показать атрибуты объекта: ``` 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'] ``` Для определения классовой принадлежности любого объекта следует использовать функцию type(): ``` type(f2) ``` Удалим объекты из рабочего пространства: ``` del f1, f2 dir() ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'os'] ``` # Пункт 3 Правила именования объектов: ``` gg1 = 1.6 hh1 = 'example' 73sr = 3 SyntaxError: invalid decimal literal - ошибка, т.к. имя не может начинаться с числа and = 7 SyntaxError: invalid syntax - ошибка, т.к. имя не может совпадать с ключевым словом языка ``` # Пункт 4 Можно просмотреть все ключевые слова: ``` 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'] keyWordList = keyword.kwlist keyWordList ['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'] type(keyWordList) ``` # Пункт 5 Выведу список встроенных идентификаторов с помощью инструкций ``` 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'] ``` Среди этих имен есть полезные функции, например: Взятие модуля ``` abs(-5) 5 ``` Длина объекта ``` len([1,2,3]) 3 ``` Максимум значений max(14,8) 14 Минимум значений ``` min(15,0) 0 ``` Возведение в степень ``` pow(5,2) 25 ``` Можно возводить в степень по модулю ``` pow(5, 2, 2) 1 ``` Округление ``` round(3,124) 3 ``` Можно указать порядок, до которого округляем (по умолчанию - до целого) ``` round(4.87945, 2) 4.88 ``` Суммирование ``` sum([7,3,5]) 15 ``` Можно указать еще и начальное значение ``` sum([7,3,5],7) 22 ``` Сортировка по возрастанию или по убыванию: ``` sorted ([3, 7, 9, 75, 0, -1]) [-1, 0, 3, 7, 9, 75] ``` Объединение объектов в кортеж ``` sorted ([3, 7, 9, 75, 0, -1], reverse = True) [75, 9, 7, 3, 0, -1] ``` ``` list1 = [1,2,3] list2 = [4,5,6] zip(list1, list2) ``` # Пункт 6. Python - регистрочувствительный язык ``` Gg1 = 45 gg1, Gg1 (1.6, 45) gg1 == Gg1 False ``` # Пункт 7.1 Логический тип: ``` bb1 = True bb2 = False type(bb1) ``` # Пункт 7.2 Целое число (десятичное) ``` ii1 = 1234567890 type(ii1) ``` Экспоненциальная форма записи числа ``` ff1 = 8.987e-12 type(ff1) Двоичное число (префикс 0b - binary) dv1 = 0b1100101 type(bb1) Восьмеричное число (0о - octal) vsm1 = 0o52765 type(vsm1) Шестнадцатеричное число (0х - hexadecimal) shest1 = 0x7109af6 type(shest1) Комплексное число cc1 = 2 - 3j type(cc1) a = 3.67 b = 0.45 cc2 = complex(a,b) cc2 (3.67+0.45j) type(cc2) ``` # Пункт 7.3 Строковые данные Одинарные и двойные кавычки взаимозаменяемы, но если открыта одинарная, то закрыта тоже должна быть одинарная ``` ss1 = "Это - строка символов" ss2 = "Это - строка символов" ss1 == ss2 True ss1a = "Это - \"строка символов\", \n \t выводимая на двух строках" print(ss1a) Это - "строка символов", выводимая на двух строках ss1b = 'Меня зовут: \n Тимошенко А.А.' print(ss1b) Меня зовут: Тимошенко А.А. ``` Обратимся к отдельным элементам с помощью квадратных кавычек (нумерация с нуля): Большую строку можно записать в тройных кавычках: mnogo="""Нетрудно заметить , что в результате операции над числами разных типов получается число, имеющее более сложный тип из тех, которые участвуют в операции.""" ``` print(mnogo) Нетрудно заметить , что в результате операции над числами разных типов получается число, имеющее более сложный тип из тех, которые участвуют в операции. ``` Обратимся к отдельным элементам с помощью квадратных кавычек (нумерация с нуля): ``` mnogo[3] 'р' ss1b[-1] - первый с конца '.' ``` Срезы: ``` ss1[6:9] 'стр' ss1[3:17:2] ' тоасм' ss1[5:-8] ' строка ' Задав шаг -1, можно вывести строку в обратном порядке: ss1[::-1] 'воловмис акортс - отЭ' ``` К элементу можно обратиться как по нумерации с начала, так и с конца: ``` ss1[17:3:-2] 'омсаот ' ss1[-4:3:-2] 'омсаот ' ``` Строка - неизменяемый тип данных: ``` ss1[4] = "=" Traceback (most recent call last): File "", line 1, in ss1[4] = "=" TypeError: 'str' object does not support item assignment ss1b_cut = ss1b [::-2] ``` Но если возникает необходимость изменить строку, то можно пересобрать ее из исходной строки: ``` ss1=ss1[:4]+'='+ss1[5:] ss1 'Это = строка символов' ``` Новый объект на основе среза из старого: ss1b_cut = ss1b [::-2] ss1b_cut '.. кеои твзяе' Собственное создание разных типов данных: ``` num10 = 26 type(num10) num16 = hex(num10) num16 '0x1a' type(num16) KeyboardInterrupt str1 = str(num10) + ' в десятичной - это ' + str(num16) + ' в шестнадцатеричной ' str1 '26 в десятичной - это 0x1a в шестнадцатеричной ' str1[5:16:3] 'дячй' ``` # Пункт 8. Списки, кортежи, словари, множества Список list - изменяемый тип данных. Это упорядоченная последовательность из элементов одного или разных типов. ``` spis1 = ["111", 'spisok', 5 - 9j] stup=[0,0,1,1,1,1,1,1,1] stup [0, 0, 1, 1, 1, 1, 1, 1, 1] spis=[1,2,3,4,5,6,7,8,9,10] spis [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] spis[-1] 10 spis1[-1] (5-9j) stup[-8::2] [0, 1, 1, 1] spis1[1]='Список' spis1 ['111', 'Список', (5-9j)] len(spis1) 3 ``` Методы списков: 1. Добавление в конец (append) ``` 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+['New item'] Только возвращает результат, но не фиксирует такое значение! ['111', 'Список', (5-9j), 'New item', 'New item'] spis1 ['111', 'Список', (5-9j), 'New item'] Конкатенация строк: spis1 += ss1b spis1 ['111', 'Список', (5-9j), 'New item', 'М', 'е', 'н', 'я', ' ', 'з', 'о', 'в', 'у', 'т', ':', ' ', '\n', ' ', 'Т', 'и', 'м', 'о', 'ш', 'е', 'н', 'к', 'о', ' ', 'А', '.', 'А', '.'] spis1 = [111, 'Список', (5-9j), 'New item'] spis1.append(ss1b) spis1 [111, 'Список', (5-9j), 'New item', 'Меня зовут: \n Тимошенко А.А.'] ``` 2. Удаление элемента по индексу (pop): ``` spis1.pop(1) 'Список' spis1 [111, (5-9j), 'New item', 'Меня зовут: \n Тимошенко А.А.'] Если указать индекс, которого нет: spis1.pop(7) Traceback (most recent call last): File "", line 1, in spis1.pop(7) IndexError: pop index out of range ``` 3. Вставка элемента в определенное место по индексу (insert) ``` help(spis1.insert) Help on built-in function insert: insert(index, object, /) method of builtins.list instance Insert object before index. spis1.insert(2, "hello") spis1 [111, (5-9j), 'hello', 'New item', 'Меня зовут: \n Тимошенко А.А.'] Если указать число большее чем длина списка, то просто вставится в конец: spis1.insert(8, "test") spis1 [111, (5-9j), 'hello', 'New item', 'Меня зовут: \n Тимошенко А.А.', 'test'] ``` 4. Удаление элемента по значению (remove) ``` help(spis1.remove) Help on built-in function remove: remove(value, /) method of builtins.list instance Remove first occurrence of value. Raises ValueError if the value is not present. spis1.remove(111) spis1 [(5-9j), 'hello', 'New item', 'Меня зовут: \n Тимошенко А.А.', 'test'] spis1.remove('kitten') Traceback (most recent call last): File "", line 1, in spis1.remove('kitten') help(spis1.extend) ``` 5. Добавление элементов объекта в конец другого объекта (extend) ``` Help on built-in function extend: extend(iterable, /) method of builtins.list instance Extend list by appending elements from the iterable. end1 = [123, "mew", (1,2)] spis1.extend(end1) spis1 [(5-9j), 'hello', 'New item', 'Меня зовут: \n Тимошенко А.А.', 'test', 123, 'mew', (1, 2)] ``` 6. Полное очищение списка (clear) ``` help(spis1.clear) Help on built-in function clear: clear() method of builtins.list instance Remove all items from list. end1.clear() end1 [] ``` 7. Сортировка списка БЕЗ создания нового объекта (sort) ``` help(spis1.sort) Help on built-in function sort: sort(*, key=None, reverse=False) method of builtins.list instance Sort the list in ascending order and return None. The sort is in-place (i.e. the list itself is modified) and stable (i.e. the order of two equal elements is maintained). If a key function is given, apply it once to each list item and sort them, ascending or descending, according to their function values. The reverse flag can be set to sort in descending order. end1 = [5, 6, 9.99999, 384, 0, -5] end1.sort(key = abs, reverse = True) end1 [384, 9.99999, 6, 5, -5, 0] ``` 8. Создание копии списка (copy) ``` help(end1.copy) Help on built-in function copy: copy() method of builtins.list instance Return a shallow copy of the list. endcopy = end1.copy() endcopy [384, 9.99999, 6, 5, -5, 0] ``` 9. Поиск индекса по значению (index) ``` help(endcopy.index) Help on built-in function index: index(value, start=0, stop=9223372036854775807, /) method of builtins.list instance Return first index of value. Raises ValueError if the value is not present. endcopy.index(0) 5 endopy.index("hehehe") Traceback (most recent call last): File "", line 1, in endopy.index("hehehe") ValueError: 'hehehe' is not in list ``` 10. Подсчет количества элементов по значению (count) ``` help(endcopy.count) Help on built-in function count: count(value, /) method of builtins.list instance Return number of occurrences of value. endcopy.count(5) 1 endcopy.count(666666) 0 ``` # Пункт 8.1 Вложенные списки: ``` spis2=[spis1,[4,5,6,7]] spis2 [[(5-9j), 'hello', 'New item', 'Меня зовут: \n Тимошенко А.А.', 'test', 123, 'mew', (1, 2)], [4, 5, 6, 7]] spis2[0][1] 'hello' spis2[0][1]=78 spis2 [[(5-9j), 78, 'New item', 'Меня зовут: \n Тимошенко А.А.', 'test', 123, 'mew', (1, 2)], [4, 5, 6, 7]] spis1 [(5-9j), 78, 'New item', 'Меня зовут: \n Тимошенко А.А.', 'test', 123, 'mew', (1, 2)] ``` Как видно, spis1 тоже изменился. Это происходит потому, что python работает не просто с объектами, а с ссылками на участки памяти. То есть, в Python списки передаются по ссылке, а не по значению. Упоминая spis1 в строке spis2=[spis1,[4,5,6,7]] мы не создаем копию spis1, а сообщаем именно тот список, поэтому его изменения в составе spis2 отобраажются на исходном spis1. # Пункт 8.2. Кортеж: последовательность как список, но неизменяемая как строка. ``` 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 >>> kortstr = ("h", "lambda", "always", 54, [1,2,3], (6,7)) SyntaxError: invalid syntax kortstr = ("h", "lambda", "always", 54, [1,2,3], (6,7)) kortstr ('h', 'lambda', 'always', 54, [1, 2, 3], (6, 7)) type(kortstr[5]) type(kortstr[4]) ``` # Пункт 8.3. Словарь (dictionary) - содержит в себе совокупность пар ``` "ключ (key) (неизменяемый)": "значение (value) (любого типа)" dic1={'Saratov':145, 'Orel':56, 'Vologda':45} dic1 {'Saratov': 145, 'Orel': 56, 'Vologda': 45} dic1[1] Traceback (most recent call last): File "", line 1, in #как видно, обратиться по индексу нельзя dic1[1] KeyError: 1 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)]) dic4 {1: ['A', 'B', 'C'], 2: [4, 5], 'Q': 'Prim', 'Stroka': 'Меня зовут: \n Тимошенко А.А.'} dic5=dict(zip(['A','B','C','Stroka'],[16,-3,9,ss1b])) dic5 {'A': 16, 'B': -3, 'C': 9, 'Stroka': 'Меня зовут: \n Тимошенко А.А.'} ``` Создание собственного словаря на основе кортежа из семи элементов и списка из пяти: ``` terms_tuple = ("mean", "median", "mode", "variance", "standard deviation", "correlation", "regression") count_list = ["one", "two", "three", "four", "five"] KeyboardInterrupt count_list = ["one", "two", "three", "four", "five"] terms_dict = dict(zip(count_list, terms_tuple)) terms_dict {'one': 'mean', 'two': 'median', 'three': 'mode', 'four': 'variance', 'five': 'standard deviation'} ``` # Пункт 8.4. Объект-множество: состоят из НЕповторяющихся неизменяемых элементов ``` mnoz1={'двигатель','датчик','линия связи','датчик','микропроцессор','двигатель'} mnoz1 {'датчик', 'линия связи', 'микропроцессор', 'двигатель'} len(mnoz1) 4 'датчик' in mnoz1 True mnoz1.add('реле') mnoz1.remove('линия связи') mnoz1 {'датчик', 'реле', 'двигатель', 'микропроцессор'} ```