diff --git a/TEMA1/report_BACKUP_1231.md b/TEMA1/report_BACKUP_1231.md new file mode 100644 index 0000000..8f0080a --- /dev/null +++ b/TEMA1/report_BACKUP_1231.md @@ -0,0 +1,140 @@ +<<<<<<< HEAD +# Отчет по теме 1 + +Савин Семён, А-02-23 + +# Основы языка программирования Python +======= +# Отчет по ЛР1 Савин С.А. + + +>>>>>>> e91ec08 (Task_2: report v1) + +## Пункты3-5 +Через командную строку вы +```py +print('Hello') +h=input('Your name is -') +Hello +Your name is -sam +exit() +``` +Программа закрыта (Вся командная строка) + +## Пункт 8: +```py +import os +os.chdir(r'C:\Users\u207-05\python-labs\TEMA1') +``` + +## Пункт 9: +Были изменены параметры текста в редакторе при помощи меню "Options" + +## Пункт 10: +Создан новый файл в редакторе написано: +```py +#This is a very profound comment +#Программа по Теме 1 Савин С.А. +print('Hello') +h = input('Your name is -') +import os +os.chdir(r'C:\Users\u207-05\python-labs\TEMA1') +``` +Модуль запущен +### Вывод: +```py += RESTART: C:/Users/u207-05/python-labs/TEMA1/Pr0.py +Hello +Your name is -sam +``` +Последняя команда выбора рабочей папки выполнена без ошибок. + +Также файл был выполнен следующим образом: +```py +import Pr0 +Hello +Your name is -sam +``` +И аналогично через клавишу F5 в открытом редакторе. + +## Пункт 11: +При помощи повторного вызова команды import вставили имя файла - "prb1" +```py +import prb1 +Как Вас зовут? Семён +Привет, Семён +``` + +## Пункт 12: +В папке __pycache__ нашел файл +pr0.cpython-311, открыл при помощи notepad++ +Содержимое: +§ + + №йєhВ г  уZ —  e d ¦ «   ed¦ « ZddlZ ej d¦ «  dS )ЪHellozYour name is -й Nz"C:\Users\u207-05\python-labs\TEMA1)ЪprintЪinputЪhЪosЪchdir© у ъ)C:\Users/u207-05/python-labs/TEMA1\Pr0.pyъr  sF рр ЂЂgЃ„ЂШ ЂEР +СФЂШ Ђ Ђ Ђ Ш Ђ„Р .С /Ф /Р /Р /Р /r + +Это резльтат компиляции, который выглядит так по причине того, что в данной папке хранятся байт-коды, используемые при запуске программы для увеличения оптимизации. + +## Пункт 13: +Пропущен по причине уже созданного файла report.md. + +## Пункт 14: +Вызвана команда help по нескольким функциям. +help(print) +Help on built-in function print in module builtins: + +print(*args, sep=' ', end='\n', file=None, flush=False) + Prints the values to a stream, or to sys.stdout by default. + + sep + string inserted between values, default a space. + end + string appended after the last value, default a newline. + file + a file-like object (stream); defaults to the current sys.stdout. + flush + whether to forcibly flush the stream. + +help(print),help(input) +Help on built-in function print in module builtins: + +print(*args, sep=' ', end='\n', file=None, flush=False) + Prints the values to a stream, or to sys.stdout by default. + + sep + string inserted between values, default a space. + end + string appended after the last value, default a newline. + file + a file-like object (stream); defaults to the current sys.stdout. + flush + whether to forcibly flush the stream. + +Help on built-in function input in module builtins: + +input(prompt='', /) + Read a string from standard input. The trailing newline is stripped. + + The prompt string, if given, is printed to standard output without a + trailing newline before reading input. + + If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError. + On *nix systems, readline is used if available. +Также была найдена запись о функции print() через f1 +## Пункт 15: +Были снова выполнены файлы из рабочей папки, проведена работа с окнами. +Результат работы tdemo_chaos: + +<<<<<<< HEAD +![Демонстрация хаоса](pic1.png) + +Результат работы часов clock из примеров для демо: + +![Часы](pic2.png) +======= +![C:\Users\u207-05\python-labs\TEMA1](pic1.png) + +Результат работы часов clock из примеров для демо: + +>>>>>>> e91ec08 (Task_2: report v1) diff --git a/TEMA1/report_BASE_1231.md b/TEMA1/report_BASE_1231.md new file mode 100644 index 0000000..e69de29 diff --git a/TEMA1/report_LOCAL_1231.md b/TEMA1/report_LOCAL_1231.md new file mode 100644 index 0000000..7033e83 --- /dev/null +++ b/TEMA1/report_LOCAL_1231.md @@ -0,0 +1,127 @@ +# Отчет по теме 1 + +Савин Семён, А-02-23 + +# Основы языка программирования Python + +## Пункты3-5 +Через командную строку вы +```py +print('Hello') +h=input('Your name is -') +Hello +Your name is -sam +exit() +``` +Программа закрыта (Вся командная строка) + +## Пункт 8: +```py +import os +os.chdir(r'C:\Users\u207-05\python-labs\TEMA1') +``` + +## Пункт 9: +Были изменены параметры текста в редакторе при помощи меню "Options" + +## Пункт 10: +Создан новый файл в редакторе написано: +```py +#This is a very profound comment +#Программа по Теме 1 Савин С.А. +print('Hello') +h = input('Your name is -') +import os +os.chdir(r'C:\Users\u207-05\python-labs\TEMA1') +``` +Модуль запущен +### Вывод: +```py += RESTART: C:/Users/u207-05/python-labs/TEMA1/Pr0.py +Hello +Your name is -sam +``` +Последняя команда выбора рабочей папки выполнена без ошибок. + +Также файл был выполнен следующим образом: +```py +import Pr0 +Hello +Your name is -sam +``` +И аналогично через клавишу F5 в открытом редакторе. + +## Пункт 11: +При помощи повторного вызова команды import вставили имя файла - "prb1" +```py +import prb1 +Как Вас зовут? Семён +Привет, Семён +``` + +## Пункт 12: +В папке __pycache__ нашел файл +pr0.cpython-311, открыл при помощи notepad++ +Содержимое: +§ + + №йєhВ г  уZ —  e d ¦ «   ed¦ « ZddlZ ej d¦ «  dS )ЪHellozYour name is -й Nz"C:\Users\u207-05\python-labs\TEMA1)ЪprintЪinputЪhЪosЪchdir© у ъ)C:\Users/u207-05/python-labs/TEMA1\Pr0.pyъr  sF рр ЂЂgЃ„ЂШ ЂEР +СФЂШ Ђ Ђ Ђ Ш Ђ„Р .С /Ф /Р /Р /Р /r + +Это резльтат компиляции, который выглядит так по причине того, что в данной папке хранятся байт-коды, используемые при запуске программы для увеличения оптимизации. + +## Пункт 13: +Пропущен по причине уже созданного файла report.md. + +## Пункт 14: +Вызвана команда help по нескольким функциям. +help(print) +Help on built-in function print in module builtins: + +print(*args, sep=' ', end='\n', file=None, flush=False) + Prints the values to a stream, or to sys.stdout by default. + + sep + string inserted between values, default a space. + end + string appended after the last value, default a newline. + file + a file-like object (stream); defaults to the current sys.stdout. + flush + whether to forcibly flush the stream. + +help(print),help(input) +Help on built-in function print in module builtins: + +print(*args, sep=' ', end='\n', file=None, flush=False) + Prints the values to a stream, or to sys.stdout by default. + + sep + string inserted between values, default a space. + end + string appended after the last value, default a newline. + file + a file-like object (stream); defaults to the current sys.stdout. + flush + whether to forcibly flush the stream. + +Help on built-in function input in module builtins: + +input(prompt='', /) + Read a string from standard input. The trailing newline is stripped. + + The prompt string, if given, is printed to standard output without a + trailing newline before reading input. + + If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError. + On *nix systems, readline is used if available. +Также была найдена запись о функции print() через f1 +## Пункт 15: +Были снова выполнены файлы из рабочей папки, проведена работа с окнами. +Результат работы tdemo_chaos: + +![Демонстрация хаоса](pic1.png) + +Результат работы часов clock из примеров для демо: + +![Часы](pic2.png) \ No newline at end of file diff --git a/TEMA1/report_REMOTE_1231.md b/TEMA1/report_REMOTE_1231.md new file mode 100644 index 0000000..269f46f --- /dev/null +++ b/TEMA1/report_REMOTE_1231.md @@ -0,0 +1,124 @@ +# Отчет по ЛР1 Савин С.А. + + + +## Пункты3-5 +Через командную строку вы +```py +print('Hello') +h=input('Your name is -') +Hello +Your name is -sam +exit() +``` +Программа закрыта (Вся командная строка) + +## Пункт 8: +```py +import os +os.chdir(r'C:\Users\u207-05\python-labs\TEMA1') +``` + +## Пункт 9: +Были изменены параметры текста в редакторе при помощи меню "Options" + +## Пункт 10: +Создан новый файл в редакторе написано: +```py +#This is a very profound comment +#Программа по Теме 1 Савин С.А. +print('Hello') +h = input('Your name is -') +import os +os.chdir(r'C:\Users\u207-05\python-labs\TEMA1') +``` +Модуль запущен +### Вывод: +```py += RESTART: C:/Users/u207-05/python-labs/TEMA1/Pr0.py +Hello +Your name is -sam +``` +Последняя команда выбора рабочей папки выполнена без ошибок. + +Также файл был выполнен следующим образом: +```py +import Pr0 +Hello +Your name is -sam +``` +И аналогично через клавишу F5 в открытом редакторе. + +## Пункт 11: +При помощи повторного вызова команды import вставили имя файла - "prb1" +```py +import prb1 +Как Вас зовут? Семён +Привет, Семён +``` + +## Пункт 12: +В папке __pycache__ нашел файл +pr0.cpython-311, открыл при помощи notepad++ +Содержимое: +§ + + №йєhВ г  уZ —  e d ¦ «   ed¦ « ZddlZ ej d¦ «  dS )ЪHellozYour name is -й Nz"C:\Users\u207-05\python-labs\TEMA1)ЪprintЪinputЪhЪosЪchdir© у ъ)C:\Users/u207-05/python-labs/TEMA1\Pr0.pyъr  sF рр ЂЂgЃ„ЂШ ЂEР +СФЂШ Ђ Ђ Ђ Ш Ђ„Р .С /Ф /Р /Р /Р /r + +Это резльтат компиляции, который выглядит так по причине того, что в данной папке хранятся байт-коды, используемые при запуске программы для увеличения оптимизации. + +## Пункт 13: +Пропущен по причине уже созданного файла report.md. + +## Пункт 14: +Вызвана команда help по нескольким функциям. +help(print) +Help on built-in function print in module builtins: + +print(*args, sep=' ', end='\n', file=None, flush=False) + Prints the values to a stream, or to sys.stdout by default. + + sep + string inserted between values, default a space. + end + string appended after the last value, default a newline. + file + a file-like object (stream); defaults to the current sys.stdout. + flush + whether to forcibly flush the stream. + +help(print),help(input) +Help on built-in function print in module builtins: + +print(*args, sep=' ', end='\n', file=None, flush=False) + Prints the values to a stream, or to sys.stdout by default. + + sep + string inserted between values, default a space. + end + string appended after the last value, default a newline. + file + a file-like object (stream); defaults to the current sys.stdout. + flush + whether to forcibly flush the stream. + +Help on built-in function input in module builtins: + +input(prompt='', /) + Read a string from standard input. The trailing newline is stripped. + + The prompt string, if given, is printed to standard output without a + trailing newline before reading input. + + If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError. + On *nix systems, readline is used if available. +Также была найдена запись о функции print() через f1 +## Пункт 15: +Были снова выполнены файлы из рабочей папки, проведена работа с окнами. +Результат работы tdemo_chaos: + +![C:\Users\u207-05\python-labs\TEMA1](pic1.png) + +Результат работы часов clock из примеров для демо: + diff --git a/TEMA8/MM0.py b/TEMA8/MM0.py new file mode 100644 index 0000000..1219d5d --- /dev/null +++ b/TEMA8/MM0.py @@ -0,0 +1,2 @@ +import MM2 +print('y=', MM2.vyhod) diff --git a/TEMA8/MM1.py b/TEMA8/MM1.py new file mode 100644 index 0000000..489fa63 --- /dev/null +++ b/TEMA8/MM1.py @@ -0,0 +1,19 @@ +def realdvig(xtt,kk1,TT,yti1,ytin1): + yp=kk1*xtt + yti1=yp+yti1 + ytin1=(yti1+TT*ytin1)/(TT+1) + return [yti1,ytin1] + +def tahogen(xtt,kk2,yti2): + yp=kk2*xtt + yti2=yp+yti2 + return yti2 + +def nechus(xtt,gran): + if xtt(-gran): + ytt=0 + elif xtt>=gran: + ytt=xtt-gran + elif xtt<=(-gran): + ytt=xtt+gran + return ytt diff --git a/TEMA8/MM2.py b/TEMA8/MM2.py new file mode 100644 index 0000000..cbba0a3 --- /dev/null +++ b/TEMA8/MM2.py @@ -0,0 +1,23 @@ +znach=input('k1,T,k2,Xm,A,F,N=').split(',') +k1=float(znach[0]) +T=float(znach[1]) +k2=float(znach[2]) +Xm=float(znach[3]) +A=float(znach[4]) +F=float(znach[5]) +N=int(znach[6]) + +import math +vhod=[] +for i in range(N): + vhod.append(A*math.sin((2*i*math.pi)/F)) + +import MM1 as mod +yi1=0;yin1=0;yi2=0 +vyhod=[] +for xt in vhod: + xt1=xt-yi2 #отрицательная обратная связь + [yi1,yin1]=mod.realdvig(xt1,k1,T,yi1,yin1) + yi2=mod.tahogen(yin1,k2,yi2) + yt=mod.nechus(yin1,Xm) + vyhod.append(yt) diff --git a/TEMA8/Mod0.py b/TEMA8/Mod0.py index 6337fc3..1087a18 100644 --- a/TEMA8/Mod0.py +++ b/TEMA8/Mod0.py @@ -1,4 +1,3 @@ -#Модуль Mod0 import Mod1 print('perm1=',Mod1.perm1) from Mod2 import alpha as al @@ -7,3 +6,4 @@ print('tt=',tt) from Mod2 import beta qq=beta(float(tt)) print('qq=',qq) +perm1 = Mod1.perm1 diff --git a/TEMA8/correlate.py b/TEMA8/correlate.py new file mode 100644 index 0000000..17f6d57 --- /dev/null +++ b/TEMA8/correlate.py @@ -0,0 +1,25 @@ +import math +def correlation(numbers1, numbers2): + if not numbers1 or not numbers2: + print('пусто') + return(0) + + n = min(len(numbers1), len(numbers2)) + + x = numbers1[:n] + y = numbers2[:n] + + meanx = sum(x)/n + meany = sum(y)/n + + sum1 = 0 + sum2 = 0 + sum3 = 0 + + for i in range (n): + sum1 += ((x[i] - meanx)*(y[i] - meany)) + sum2 += ((x[i] - meanx)**2) + sum3 += ((y[i] - meany)**2) + print(sum1,sum2,sum3) + return (sum1/math.sqrt(sum2*sum3)) + diff --git a/TEMA8/img1.png b/TEMA8/img1.png new file mode 100644 index 0000000..751fc6a Binary files /dev/null and b/TEMA8/img1.png differ diff --git a/TEMA8/img2.png b/TEMA8/img2.png new file mode 100644 index 0000000..604f5bd Binary files /dev/null and b/TEMA8/img2.png differ diff --git a/TEMA8/img3.png b/TEMA8/img3.png new file mode 100644 index 0000000..1eb18b3 Binary files /dev/null and b/TEMA8/img3.png differ diff --git a/TEMA8/img4.png b/TEMA8/img4.png new file mode 100644 index 0000000..5d3463f Binary files /dev/null and b/TEMA8/img4.png differ diff --git a/TEMA8/mainfile.py b/TEMA8/mainfile.py new file mode 100644 index 0000000..94fb722 --- /dev/null +++ b/TEMA8/mainfile.py @@ -0,0 +1,17 @@ +from readerfile import reader +from correlate import correlation + +def main(): + print("_________Калькулятор корреляции_________") + file1 = input("Первый файл: ").strip() + file2 = input("Второй файл: ").strip() + + numbers1 = reader(file1) + numbers2 = reader(file2) + + print(numbers1) + print(numbers2) + + cor = correlation(numbers1, numbers2) + + print("Коэффициент корреляции - ", cor) diff --git a/TEMA8/num1.txt b/TEMA8/num1.txt new file mode 100644 index 0000000..648b033 --- /dev/null +++ b/TEMA8/num1.txt @@ -0,0 +1,3 @@ +44 50 43 30 24 +10 9 1 5 +29 19 14 21 \ No newline at end of file diff --git a/TEMA8/num2.txt b/TEMA8/num2.txt new file mode 100644 index 0000000..397be62 --- /dev/null +++ b/TEMA8/num2.txt @@ -0,0 +1,3 @@ +30 60 58 40 34 +20 19 16 15 +39 28 24 31 \ No newline at end of file diff --git a/TEMA8/readerfile.py b/TEMA8/readerfile.py new file mode 100644 index 0000000..eedd2f8 --- /dev/null +++ b/TEMA8/readerfile.py @@ -0,0 +1,9 @@ +def reader(filename): + num = [] + with open(filename, 'r', encoding = 'utf-8') as file: + for line in file: + elements = line.strip().split() + for elem in elements: + number = float(elem) + num.append(number) + return num diff --git a/TEMA8/report.md b/TEMA8/report.md new file mode 100644 index 0000000..8881b88 --- /dev/null +++ b/TEMA8/report.md @@ -0,0 +1,294 @@ +# Тема 8 + +Савин Семён, А-02-23 + +## Пункт 1. Подготовка к работе. + +```py +>>> import os,sys +>>> import importlib as imp +>>> os.chdir('C:\\Users\\somas\\python-labs\\TEMA8') +>>> os.getcwd() +'C:\\Users\\somas\\python-labs\\TEMA8' +``` + +## Пункт 2.1. Запуск модуля на выполнение путем его импорта + +![Скриншот содержимого файла Mod1.py](img1.png) + +```py +>>> import Mod1 +Mod1:Введите значение = 5 +Mod1:Значение perm1= 5 +>>> type(Mod1) + +>>> dir(Mod1) +['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'perm1'] +>>> Mod1.perm1 +'5' +>>> import Mod1 +>>> imp.reload(Mod1) +Mod1:Введите значение = 3 +Mod1:Значение perm1= 3 + +>>> Mod1.perm1 +'3' +``` + +## 2.2. Удаление модуля из словаря + +```py +>>> print(sorted(sys.modules.keys())) +['Mod1', '__main__', '_abc', '_ast', '_bisect', '_bootlocale', '_bz2', '_codecs', '_collections', '_collections_abc', '_compat_pickle', '_compression', '_datetime', '_frozen_importlib', '_frozen_importlib_external', '_functools', '_heapq', '_imp', '_io', '_locale', '_lzma', '_opcode', '_operator', '_pickle', '_queue', '_random', '_sha512', '_signal', '_sitebuiltins', '_socket', '_sre', '_stat', '_string', '_struct', '_thread', '_tkinter', '_warnings', '_weakref', '_weakrefset', '_winapi', 'abc', 'ast', 'bdb', 'binascii', 'bisect', 'builtins', 'bz2', 'codecs', 'collections', 'collections.abc', 'configparser', 'contextlib', 'copyreg', 'datetime', 'dis', 'encodings', 'encodings.aliases', 'encodings.cp1251', 'encodings.latin_1', 'encodings.utf_8', 'enum', 'errno', 'fnmatch', 'functools', 'genericpath', 'heapq', 'idlelib', 'idlelib.autocomplete', 'idlelib.autocomplete_w', 'idlelib.calltip', 'idlelib.calltip_w', 'idlelib.config', 'idlelib.debugger', 'idlelib.debugger_r', 'idlelib.debugobj', 'idlelib.debugobj_r', 'idlelib.hyperparser', 'idlelib.iomenu', 'idlelib.macosx', 'idlelib.multicall', 'idlelib.pyparse', 'idlelib.rpc', 'idlelib.run', 'idlelib.scrolledlist', 'idlelib.stackviewer', 'idlelib.tooltip', 'idlelib.tree', 'idlelib.util', 'idlelib.window', 'idlelib.zoomheight', 'importlib', 'importlib._bootstrap', 'importlib._bootstrap_external', 'importlib.abc', 'importlib.machinery', 'importlib.util', 'inspect', 'io', 'itertools', 'keyword', 'linecache', 'lzma', 'marshal', 'math', 'msvcrt', 'nt', 'ntpath', 'opcode', 'operator', 'os', 'os.path', 'pickle', 'pkgutil', 'platform', 'plistlib', 'posixpath', 'pydoc', 'pyexpat', 'pyexpat.errors', 'pyexpat.model', 'queue', 'random', 're', 'reprlib', 'select', 'selectors', 'shlex', 'shutil', 'signal', 'site', 'socket', 'socketserver', 'sre_compile', 'sre_constants', 'sre_parse', 'stat', 'string', 'struct', 'subprocess', 'sys', 'sysconfig', 'tempfile', 'textwrap', 'threading', 'time', 'tkinter', 'tkinter.constants', 'token', 'tokenize', 'traceback', 'types', 'typing', 'typing.io', 'typing.re', 'urllib', 'urllib.parse', 'warnings', 'weakref', 'winreg', 'xml', 'xml.parsers', 'xml.parsers.expat', 'xml.parsers.expat.errors', 'xml.parsers.expat.model', 'zipimport', 'zlib'] +>>> sys.modules.pop('Mod1') + +>>> print(sorted(sys.modules.keys())) +['__main__', '_abc', '_ast', '_bisect', '_bootlocale', '_bz2', '_codecs', '_collections', '_collections_abc', '_compat_pickle', '_compression', '_datetime', '_frozen_importlib', '_frozen_importlib_external', '_functools', '_heapq', '_imp', '_io', '_locale', '_lzma', '_opcode', '_operator', '_pickle', '_queue', '_random', '_sha512', '_signal', '_sitebuiltins', '_socket', '_sre', '_stat', '_string', '_struct', '_thread', '_tkinter', '_warnings', '_weakref', '_weakrefset', '_winapi', 'abc', 'ast', 'bdb', 'binascii', 'bisect', 'builtins', 'bz2', 'codecs', 'collections', 'collections.abc', 'configparser', 'contextlib', 'copyreg', 'datetime', 'dis', 'encodings', 'encodings.aliases', 'encodings.cp1251', 'encodings.latin_1', 'encodings.utf_8', 'enum', 'errno', 'fnmatch', 'functools', 'genericpath', 'heapq', 'idlelib', 'idlelib.autocomplete', 'idlelib.autocomplete_w', 'idlelib.calltip', 'idlelib.calltip_w', 'idlelib.config', 'idlelib.debugger', 'idlelib.debugger_r', 'idlelib.debugobj', 'idlelib.debugobj_r', 'idlelib.hyperparser', 'idlelib.iomenu', 'idlelib.macosx', 'idlelib.multicall', 'idlelib.pyparse', 'idlelib.rpc', 'idlelib.run', 'idlelib.scrolledlist', 'idlelib.stackviewer', 'idlelib.tooltip', 'idlelib.tree', 'idlelib.util', 'idlelib.window', 'idlelib.zoomheight', 'importlib', 'importlib._bootstrap', 'importlib._bootstrap_external', 'importlib.abc', 'importlib.machinery', 'importlib.util', 'inspect', 'io', 'itertools', 'keyword', 'linecache', 'lzma', 'marshal', 'math', 'msvcrt', 'nt', 'ntpath', 'opcode', 'operator', 'os', 'os.path', 'pickle', 'pkgutil', 'platform', 'plistlib', 'posixpath', 'pydoc', 'pyexpat', 'pyexpat.errors', 'pyexpat.model', 'queue', 'random', 're', 'reprlib', 'select', 'selectors', 'shlex', 'shutil', 'signal', 'site', 'socket', 'socketserver', 'sre_compile', 'sre_constants', 'sre_parse', 'stat', 'string', 'struct', 'subprocess', 'sys', 'sysconfig', 'tempfile', 'textwrap', 'threading', 'time', 'tkinter', 'tkinter.constants', 'token', 'tokenize', 'traceback', 'types', 'typing', 'typing.io', 'typing.re', 'urllib', 'urllib.parse', 'warnings', 'weakref', 'winreg', 'xml', 'xml.parsers', 'xml.parsers.expat', 'xml.parsers.expat.errors', 'xml.parsers.expat.model', 'zipimport', 'zlib'] +>>> import Mod1 +Mod1:Введите значение = 4 +Mod1:Значение perm1= 4 +>>> sys.modules.pop('Mod1') + +``` + +## 2.3. Запуск модуля с помощью exec + +```py +>>> exec(open('Mod1.py').read()) +Mod1:Введите значение = 8 +Mod1:Значение perm1= 8 +>>> exec(open('Mod1.py', encoding= 'utf-8').read()) +Mod1:Введите значение = 4 +Mod1:Значение perm1= 4 +>>> exec(open('Mod1.py', encoding= 'utf-8').read()) +Mod1:Введите значение = 50 +Mod1:Значение perm1= 50 +>>> exec(open('Mod1.py', encoding= 'utf-8').read()) +Mod1:Введите значение = 10 +Mod1:Значение perm1= 10 +``` + +## 2.4. Запуск модуля с помощью from - import + +```py +>>> from Mod1 import perm1 +Mod1:Введите значение = 1 +Mod1:Значение perm1= 1 +>>> dir() +['Mod1', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '__warningregistry__', 'imp', 'os', 'perm1', 'sys'] +>>> perm1 +'1' +``` +![Скриншот содержания файла Mod2.py](img2.png) + +```py +>>> from Mod2 import beta +>>> g=beta(2) +****BETA**** +>>> g +535.4916555247646 +>>> alpha() +Traceback (most recent call last): + File "", line 1, in + alpha() +NameError: name 'alpha' is not defined +>>> from Mod2 import alpha +>>> from Mod2 import alpha as al +>>> al() +****ALPHA**** +Значение t=5 +'5' +>>> del al,beta +>>> from Mod2 import alpha as al, beta as bt +>>> from Mod2 import * +>>> tt=alpha() +****ALPHA**** +Значение t=0.12 +>>> uu=beta(float(tt)) +****BETA**** +>>> uu +1.4578913609506803 +>>> +``` + +## 3.1. Создание многомодульных программ + +![Скриншот содержимого файла Mod0.py](img3.png) + +```py +>>> sys.modules.pop('Mod1') + +>>> sys.modules.pop('Mod2') + +>>> import Mod0 +Mod1:Введите значение = 10 +Mod1:Значение perm1= 10 +perm1= 10 +****ALPHA**** +Значение t=6 +tt= 6 +****BETA**** +qq= 153552935.39544657 +>>> Mod0.tt; Mod0.qq; Mod0.Mod1.perm1 +'6' +153552935.39544657 +'10' +``` + +## 3.2. Создание модулей и реализация программы модели САУ + +![Скриншот содержания файла MM1.py](img4.png) + +```py +>>> import MM2 +k1,T,k2,Xm,A,F,N=0.4, 30, 0.6, 6, 1000, 7, 16 +>>> print('y=', MM2.vyhod) +y= [0, 4.088148160877804, 26.352485391214998, 53.16854540749361, 72.7344196620431, 77.69321318122259, 70.35974149591577, 60.62750525878967, 58.14620628522886, 64.67689441760423, 72.40046930133941, 69.47447962424967, 48.67692603876396, 12.652572207611655, -16.163653614270103, -51.357437173804996] +``` + +## 3.3. Области действия объектов в модулях + +Была изменена функция alpha в файле Mod2.py + +```py +def alpha(): + print('****ALPHA****') + t=input('Значение t=') + n=beta(6) + print(n) + return t +``` + +После запуска модуля + +```py +>>> alpha() +****ALPHA**** +Значение t=10 +****BETA**** +153552935.39544657 +'10' +``` + +Убрали изменения из alpha, изменили beta + +```py +def beta(q): + print('****BETA****') + import math + expi=q*math.pi + alpha() + return math.exp(expi) +``` + +результат + +```py +>>> beta(6) +****BETA**** +****ALPHA**** +Значение t=10 +153552935.39544657 +``` + +Добавили функцию печати в Mod0 + +```py +import Mod1 +print('perm1=',Mod1.perm1) +from Mod2 import alpha as al +tt=al() +print('tt=',tt) +from Mod2 import beta +qq=beta(float(tt)) +print('qq=',qq) +print(t,expi) +``` + +получено + +```py +Mod1:Введите значение = 10 +Mod1:Значение perm1= 10 +perm1= 10 +****ALPHA**** +Значение t=10 +tt= 10 +****BETA**** +****ALPHA**** +Значение t=10 +qq= 44031505860631.98 +Traceback (most recent call last): + File "C:\Users\somas\python-labs\TEMA8\Mod0.py", line 9, in + print(t,expi) +NameError: name 't' is not defined +``` + +В модуле Mod0 perm1 была увеличена в 3 раза + +```py +Mod1:Введите значение = 10 +Mod1:Значение perm1= 10 +perm1= 10 +****ALPHA**** +Значение t=8 +tt= 8 +****BETA**** +qq= 82226315585.59491 +perm1*3= 101010 +``` + +так получилось, так как perm1 - строка + +изменим qq,tt,perm1 в командной строке + +```py +Mod1:Введите значение = 5 +Mod1:Значение perm1= 5 +perm1= 5 +****ALPHA**** +Значение t=8 +tt= 8 +****BETA**** +qq= 82226315585.59491 +>>> perm1 = perm1*2 +Traceback (most recent call last): + File "", line 1, in + perm1 = perm1*2 +NameError: name 'perm1' is not defined +>>> tt = tt*2 +>>> tt +'88' +>>> qq = qq*2; qq +164452631171.18982 +``` + +теперь изменим Mod0.py так, чтобы perm1 можно было изменить + +```py +import Mod1 +print('perm1=',Mod1.perm1) +from Mod2 import alpha as al +tt=al() +print('tt=',tt) +from Mod2 import beta +qq=beta(float(tt)) +print('qq=',qq) +perm1 = Mod1.perm1 +``` + +результат: + +```py +Mod1:Введите значение = 5 +Mod1:Значение perm1= 5 +perm1= 5 +****ALPHA**** +Значение t=10 +tt= 10 +****BETA**** +qq= 44031505860631.98 +>>> perm1 = perm1*2 +>>> perm1 +'55' +``` diff --git a/TEMA8/task.md b/TEMA8/task.md new file mode 100644 index 0000000..a923b19 --- /dev/null +++ b/TEMA8/task.md @@ -0,0 +1,93 @@ +#Тема 8 общее задание + +## Задание + +Разработайте программу, состоящую из трех модулей: +- Модуль 1 содержит функцию считывания числового списка из текстового файла с заданным именем (аргумент функции – имя файла). Элементы в файле могут располагаться по несколько на строке с разделением пробелом. Числа элементов в строках могут быть разными. Получен-ный список должен возвращаться в вызывающую программу. +- Модуль 2 содержит функцию расчета коэффициента корреляции по двум числовым спискам (аргументы функции – имена двух списков). Числа элементов в списках могут различаться. Значение коэффициента должно возвращаться в вызывающую программу. +- Модуль 3 запрашивает у пользователя и вводит имена двух файлов с исходными данными, дважды вызывает функцию из модуля 1 и считывает два списка из двух текстовых файлов. За-тем вызывает функцию расчета коэффициента корреляции с помощью функции из модуля 2 и отображает рассчитанное значение на экране с округлением до трех цифр после точки. +Подготовьте два текстовых файла с числовыми данными и проверьте по ним работу программы. + +## Решение + +Модуль чтения readerfile.py + +```py +def reader(filename): + num = [] + with open(filename, 'r', encoding = 'utf-8') as file: + for line in file: + elements = line.strip().split() + for elem in elements: + number = float(elem) + num.append(number) + return num +``` + +Модуль калькулятора корреляции correlate.py + +```py +import math +def correlation(numbers1, numbers2): + if not numbers1 or not numbers2: + print('пусто') + return(0) + + n = min(len(numbers1), len(numbers2)) + + x = numbers1[:n] + y = numbers2[:n] + + meanx = sum(x)/n + meany = sum(y)/n + + sum1 = 0 + sum2 = 0 + sum3 = 0 + + for i in range (n): + sum1 += ((x[i] - meanx)*(y[i] - meany)) + sum2 += ((x[i] - meanx)**2) + sum3 += ((y[i] - meany)**2) + print(sum1,sum2,sum3) + return (sum1/math.sqrt(sum2*sum3)) +``` + +Главный модуль mainfile.py + +```py +from readerfile import reader +from correlate import correlation + +def main(): + print("_________Калькулятор корреляции_________") + file1 = input("Первый файл: ").strip() + file2 = input("Второй файл: ").strip() + + numbers1 = reader(file1) + numbers2 = reader(file2) + + print(numbers1) + print(numbers2) + + cor = correlation(numbers1, numbers2) + + print("Коэффициент корреляции - ", cor) +``` + +Результат работы программы: + + +```py +>>> import mainfile +>>> mainfile.main() +_________Калькулятор корреляции_________ +Первый файл: num1.txt +Второй файл: num2.txt +[44.0, 50.0, 43.0, 30.0, 24.0, 10.0, 9.0, 1.0, 5.0, 29.0, 19.0, 14.0, 21.0] +[30.0, 60.0, 58.0, 40.0, 34.0, 20.0, 19.0, 16.0, 15.0, 39.0, 28.0, 24.0, 31.0] +2420.0 2930.0 2519.6923076923076 +Коэффициент корреляции - 0.8906514939994264 +``` + +Выводится содержимое файлов, а также суммы, полученные в correlate.py, для проверки достоверности работы расчетов \ No newline at end of file