diff --git a/TEMA4/Ris1.png b/TEMA4/Ris1.png new file mode 100644 index 0000000..49ba5d5 Binary files /dev/null and b/TEMA4/Ris1.png differ diff --git a/TEMA4/Ris2.png b/TEMA4/Ris2.png new file mode 100644 index 0000000..6ed62d0 Binary files /dev/null and b/TEMA4/Ris2.png differ diff --git a/TEMA4/Ris3.png b/TEMA4/Ris3.png new file mode 100644 index 0000000..93cebca Binary files /dev/null and b/TEMA4/Ris3.png differ diff --git a/TEMA4/bar.png b/TEMA4/bar.png new file mode 100644 index 0000000..8dec2c7 Binary files /dev/null and b/TEMA4/bar.png differ diff --git a/TEMA4/hist.png b/TEMA4/hist.png new file mode 100644 index 0000000..9aed6f7 Binary files /dev/null and b/TEMA4/hist.png differ diff --git a/TEMA4/protocol.py b/TEMA4/protocol.py new file mode 100644 index 0000000..0f8e764 --- /dev/null +++ b/TEMA4/protocol.py @@ -0,0 +1 @@ +Тема 4 Соловьёва Е. Д. diff --git a/TEMA4/report.md b/TEMA4/report.md new file mode 100644 index 0000000..7e8c42b --- /dev/null +++ b/TEMA4/report.md @@ -0,0 +1,285 @@ +# Отчёт по Теме 4 +Соловьёва Екатерина А-01-23 +## 1. Запуск интерактивной оболочки IDLE +## 2. Стандартные функции, находящиеся в модуле builtins +## 2.1. Функция round – округление числа с заданной точностью. +Получим справку по назначению этой функции +```py +help('round') +Help on built-in function round in module builtins: + +round(number, ndigits=None) + Round a number to a given precision in decimal digits. + + The return value is an integer if ndigits is omitted or None. Otherwise + the return value has the same type as the number. ndigits may be negative. +```py +s=round(123.456,1) +ss=round(123.456,0) +type(ss) + +type(s) + +``` +оба числа типа float. Отличие только в значении после запятой +```py +round(123.456) +123 +type(123) + +``` +Без второго аргумента возвращает целое число. +## 2.2. Функция range – создание последовательности целых чисел с заданным шагом +```py +gg=range(76,123,9) +gg +range(76, 123, 9) +list(gg) +[76, 85, 94, 103, 112, 121] +``` +эта инструкция создает, так называемый, «итерируемый объект» класса range. Чтобы увидеть получившуюся последовательность чисел, его надо преобразовать, например, в список +```py +range(23) +range(0, 23) +list(range(23)) +[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22] +``` +Значения: от 0 до 22 +Шаг: 1 + +## 2.3. Функция zip +zip – создание общего объекта, элементами которого являются кортежи, составленные из элемен-тов двух или более объектов-последовательностей (zip – застежка-«молния»). Длина результиру-ющего объекта равна длине самого короткого объекта из двух аргументов функции. +```py +list(gg) +[76, 85, 94, 103, 112, 121] +qq = ["Соловьёва", "Лыкова", "Филиппова", "Мельников"] +ff=zip(gg,qq) +ff + +tuple(ff) +((76, 'Соловьёва'), (85, 'Лыкова'), (94, 'Филиппова'), (103, 'Мельников')) +ff[0] +Traceback (most recent call last): + File "", line 1, in + ff[0] +TypeError: 'zip' object is not subscriptable +``` +Количество элементов: 3 (по длине короткого списка gg) +ff[0] вызовет ошибку, к объекту zip нельзя обращаться по индексу + +## 2.4. Функция eval – вычисление значения выражения, корректно записанного на языке Python и представленного в виде символьной строки. +```py +fff=float(input('коэффициент усиления=')); dan=eval('5*fff-156') +коэффициент усиления=5 +fff +5.0 +dan +-131.0 +``` + +## 2.5. Функция exec – чтение и выполнение объекта-аргумента функции (Этот объект должен представлять собой строку символов с совокупностью инструкций на языке Python) +```py +exec(input('введите инструкции:')) +введите инструкции:perem=-123.456;gg=round(abs(perem)+98,3) +gg +221.456 +``` +## 2.6. Самостоятельное изучение функций abs, pow, max, min, sum, divmod, len, map. +```py +gg +221.456 +abs(-5) +5 +pow(2, 3) +8 +max([1, 5, 2]) +5 +min([1, 5, 2]) +1 +sum([1, 2, 3]) +6 +divmod(10, 3) # частное и остаток +(3, 1) +len("abc") +3 +list(map(str, [1, 2, 3])) # применяет функцию к каждому элементу +['1', '2', '3'] +``` +## 3. Функции из стандартного модуля math – совокупность разнообразных математических функций. +```py +math.sin(3.14) +0.0015926529164868282 +math.acos(0.5) +1.0471975511965979 +math.degrees(1) +57.29577951308232 +math.radians(57.29577951308232) +1.0 +math.exp(1) +2.718281828459045 +math.log(2.302585092994046) # натуральный логарифм +0.834032445247956 +math.log10(100) +2.0 +math.sqrt(16) +4.0 +math.ceil(1.2) # округление вверх +2 +math.floor(0.9) # округление вниз +0 +math.pi +3.141592653589793 +math.sin(2 * math.pi / 7 + math.exp(0.23)) +0.8334902641414562 +``` +## 4. Функции из модуля cmath – совокупность функций для работы с комплексными числами. +```py +import cmath +dir(cmath) +['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'inf', 'infj', 'isclose', 'isfinite', 'isinf', 'isnan', 'log', 'log10', 'nan', 'nanj', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau'] +cmath.sqrt(1.2-0.5j) +(1.118033988749895-0.22360679774997896j) +cmath.phase(1-0.5j) # угол в радианах +-0.4636476090008061 +``` +## 5. Стандартный модуль random – совокупность функций для выполнения операций с псевдослучайными числами и выборками. +```py +import random +dir(random) +['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_ONE', '_Sequence', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_fabs', '_floor', '_index', '_inst', '_isfinite', '_lgamma', '_log', '_log2', '_os', '_parse_args', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', 'betavariate', 'binomialvariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'main', 'normalvariate', 'paretovariate', 'randbytes', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate'] +help(random.seed) +Help on method seed in module random: + +seed(a=None, version=2) method of random.Random instance + Initialize internal state from a seed. + + The only supported seed types are None, int, float, + str, bytes, and bytearray. + + None or no argument seeds from current time or from an operating + system specific randomness source if available. + + If *a* is an int, all bits are used. + + For version 2 (the default), all of the bits are used if *a* is a str, + bytes, or bytearray. For version 1 (provided for reproducing random + sequences from older versions of Python), the algorithm for str and + bytes generates a narrower range of seeds. + +random.seed() #эта функция не имеет возвращаемых значений +``` +Далее самостоятельно изучу и попробую применить следующие функции: random (равно-мерно распределенное случайное число), uniform (равномерно распределенное случайное число), randint (случайные целые числа), gauss (нормально распределенное случайное число), randint (случайное целое число), choice (случайный выбор из совокупности), shuffle (случайная переста-новка элементов списка), sample (случайный выбор подмножества элементов), betavariate(случайное число с бета-распределением), gammavariate(случайное число с гамма-распределением). +```py +random.random() +0.6199792494543297 +random.uniform(1, 10) +7.745269197841402 +random.randint(1, 6) +3 +random.gauss(0, 1) +1.0442172814729307 +random.choice(['a','b','c']) +'b' +lst = [1,2,3]; random.shuffle(lst) +lst +[3, 2, 1] +random.sample([1,2,3,4], 2) +[4, 2] +random.betavariate(2, 5) +0.27219690103691246 +random.gammavariate(2, 1) +2.5239555636492557 +``` +Создам список с 4 случайными значениями, подчиняющимися, соответственно, равномерному, нормальному, бета и гамма – распределениям и с любыми допустимыми значениями параметров этих распределений. +```py +spisok = [random.uniform(1, 10), random.gauss(0, 1), random.betavariate(2, 5), random.gammavariate(2, 1)] +spisok +[4.813064235823525, -0.2439125318449509, 0.12581423894318752, 1.940336067871031] +``` +## 6. Функции из модуля time – работа с календарем и со временем. +```py +import time +dir(time) +['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'monotonic_ns', 'perf_counter', 'perf_counter_ns', 'process_time', 'process_time_ns', 'sleep', 'strftime', 'strptime', 'struct_time', 'thread_time', 'thread_time_ns', 'time', 'time_ns', 'timezone', 'tzname'] +c1=time.time() +c2=time.time()-c1 +c2 +18.061716318130493 +c1 +1760287587.2442193 +dat=time.gmtime() +dat +time.struct_time(tm_year=2025, tm_mon=10, tm_mday=12, tm_hour=16, tm_min=51, tm_sec=23, tm_wday=6, tm_yday=285, tm_isdst=0) +dat.tm_mon +10 +local_time = time.localtime() +local_time +time.struct_time(tm_year=2025, tm_mon=10, tm_mday=12, tm_hour=19, tm_min=54, tm_sec=1, tm_wday=6, tm_yday=285, tm_isdst=0) +print(f"Год: {local_time.tm_year}") +Год: 2025 +``` +Изучу и попробую применить функции: asctime (преобразование представления времени из кортежа в строку) , ctime (преобразование времени в секундах, прошедшего с начала эпохи, в строку), sleep (прерывание работы программы на заданное время), mktime (преобразова-ние времени из типа кортежа или struct_time в число секунд с начала эпохи). Обратное преобразование из секунд в местное время осуществляется той же функцией localtime() +time.localtime(c1) +```py +c1 = time.time() +local_struct = time.localtime(c1) +local_struct +time.struct_time(tm_year=2025, tm_mon=10, tm_mday=12, tm_hour=19, tm_min=59, tm_sec=42, tm_wday=6, tm_yday=285, tm_isdst=0) +time_str = time.asctime(local_struct) +time_str +'Sun Oct 12 19:59:42 2025' +time_str2 = time.ctime(c1) +time.sleep(2) +seconds = time.mktime(local_struct) +seconds +1760288382.0 +new_struct = time.localtime(seconds) +new_struct +time.struct_time(tm_year=2025, tm_mon=10, tm_mday=12, tm_hour=19, tm_min=59, tm_sec=42, tm_wday=6, tm_yday=285, tm_isdst=0) +``` +## 7. Графические функции. +```py +import pylab +x=list(range(-3,55,4)) +t=list(range(15)) +x +[-3, 1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53] +t +[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] +pylab.plot(t,x) +[] +pylab.title + +pylab.title('Первый график') +Text(0.5, 1.0, 'Первый график') +pylab.xlabel('время') +Text(0.5, 0, 'время') +pylab.ylabel('сигнал') +Text(0, 0.5, 'сигнал') +pylab.show() +``` +попробую применить функции hist и bar для построения гистограмм и столбиковых диаграмм. +```py +data = [1, 2, 2, 3, 3, 3, 4, 4, 5] +pylab.hist(data,5) +(array([1., 2., 3., 2., 1.]), array([1. , 1.8, 2.6, 3.4, 4.2, 5. ]), ) +pylab.show() +c = ['A', 'B', 'C'] +v = [10, 25, 15] +pylab.bar(c, v) + +pylab.show() +``` + +## 8. Самостоятельное изучение состава статистического модуля statistics. +```py +data = [1, 2, 2, 3, 3, 3, 4, 4, 5] +import statistics +sred = statistics.mean(data) # среднее значение +moda = statistics.mode(data) # Мода (наиболее частое значение) +often +3 +mediana = statistics.median(data) # медиана +mediana +3 +``` \ No newline at end of file