diff --git a/TEMA4/pictures/image-1.png b/TEMA4/pictures/image-1.png new file mode 100644 index 0000000..6aa8f95 Binary files /dev/null and b/TEMA4/pictures/image-1.png differ diff --git a/TEMA4/pictures/image.png b/TEMA4/pictures/image.png new file mode 100644 index 0000000..9b59a31 Binary files /dev/null and b/TEMA4/pictures/image.png differ diff --git a/TEMA4/pictures/{39A2FC52-D033-47D6-AE7A-2C18DFB8849C}.png b/TEMA4/pictures/{39A2FC52-D033-47D6-AE7A-2C18DFB8849C}.png new file mode 100644 index 0000000..c242f64 Binary files /dev/null and b/TEMA4/pictures/{39A2FC52-D033-47D6-AE7A-2C18DFB8849C}.png differ diff --git a/TEMA4/pictures/{B16269AB-FF3F-4D96-AFB1-CF5AF8E3C145}.png b/TEMA4/pictures/{B16269AB-FF3F-4D96-AFB1-CF5AF8E3C145}.png new file mode 100644 index 0000000..1e94211 Binary files /dev/null and b/TEMA4/pictures/{B16269AB-FF3F-4D96-AFB1-CF5AF8E3C145}.png differ diff --git a/TEMA4/pictures/{DE7F74DD-ADCD-4FD3-B072-0FE157B24F01}.png b/TEMA4/pictures/{DE7F74DD-ADCD-4FD3-B072-0FE157B24F01}.png new file mode 100644 index 0000000..8e40d5d Binary files /dev/null and b/TEMA4/pictures/{DE7F74DD-ADCD-4FD3-B072-0FE157B24F01}.png differ diff --git a/TEMA4/report.md b/TEMA4/report.md index ed70308..958081d 100644 --- a/TEMA4/report.md +++ b/TEMA4/report.md @@ -4,4 +4,319 @@ ## Тема 4. Встроенные функции -## 1. \ No newline at end of file +## 2. Стандартные функции. +### 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. + + round(123.456,1) + 123.5 + round(123.456,0) + 123.0 + type(round(123.456,0)) + + type(round(123.456,1)) + + round(123.456) + 123 + type(round(123.456)) + +``` + +### 2.2. Функция создания последовательности целых чисел с заданным шагом range(). + +```py + gg=range(76,123,9) + gg + range(76, 123, 9) + type(gg) + + list(gg) + [76, 85, 94, 103, 112, 121] + range(23) + range(0, 23) + #range(23) создает последовательность целых чисел от 0 до 22 с шагом 1 + 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] +``` + +### 2.3.Функция создания общего объекта, элементами которого являются кортежи zip(). + +```py +qq = ["Коломейцев", "Степанов", "Дюрр", "Козловский"] +ff = zip(gg,qq) +ff + +tuple(ff) +((76, 'Коломейцев'), (85, 'Степанов'), (94, 'Дюрр'), (103, 'Козловский')) +ff[1] +Traceback (most recent call last): + File "", line 1, in + ff[1] +TypeError: 'zip' object is not subscriptable + +``` + +Длина результирующего объекта равна длине самого короткого объекта из списка аргументов, переданных функции. + +### 2.4. Функция вычисляющая значения выражения, корректно записанного на языке Python и представленного в виде символьной строки eval(). + +```py +fff=float(input('коэффициент усиления=')); dan=eval('5*fff-156') +коэффициент усиления=52 +dan +104.0 +``` +### 2.5. Похожая на eval() функция чтения и выполнения объекта-аргумента функции exec(). +```py +exec(input('введите инструкции:')) + введите инструкции:perem=-123.456;gg=round(abs(perem)+98,3) +gg + 221.456 +type(gg) + +``` +### 2.6. Самостоятельное изучение математических функций +```py +abs(-52) # Получение модуля числа + 52 +pow(52, 2) # Возведение числа в степень + 2704 +max(-100, 5, 7.53, 52) # Максимальное числоиз последовательности + 52 +min(-100, 5, 7.53, 52) # Минимальное числоиз последовательности + 1 +sum([-100, 5, 7.53, 52]) # Суммирование элементов последовательности +-35.47 + +divmod(52, 4) +(13, 0) # Получение кортежа с двумя элементами: результатом целочисленного деления и деления с остатком +len([-100, 5, 7.53, 52]) # Длина +4 +def power(x): + return x ** 5.2 + +map(power, [-100, 5, 7.53, 52]) + +list(map(power, [-100, 5, 7.53, 52])) +[(-20321588110.31095-14764497998.748983j), 4311.655192066298, 36252.159010564086, 837948613.8879423] +``` +## 3. Изучение функций из стандартного модуля math. +```py +import math +dir(math) + ['__doc__', '__loader__', '__name__','__package__', '__spec__', 'acos','acosh', 'asin', 'asinh', 'atan','atan2', 'atanh', 'cbrt', 'ceil', 'comb','copysign', 'cos', 'cosh', 'degrees','dist', 'e', 'erf', 'erfc', 'exp','exp2', 'expm1', 'fabs', 'factorial','floor', 'fmod', 'frexp', 'fsum','gamma', 'gcd', 'hypot', 'inf','isclose', 'isfinite', 'isinf', 'isnan','isqrt', 'lcm', 'ldexp', 'lgamma', 'log','log10', 'log1p', 'log2', 'modf', 'nan','nextafter', 'perm', 'pi', 'pow', 'prod','radians', 'remainder', 'sin', 'sinh','sqrt', 'tan', 'tanh', 'tau', 'trunc','ulp'] +help(math.factorial) + Help on built-in function factorial inmodule math: + factorial(n, /) + Find n!. + + Raise a ValueError if x is negativeor non-integral. +math.factorial(5) # Расчет факториала числа + 120 +math.sin(math.pi / 6) # Расчет синуса числа + 0.49999999999999994 +math.acos(0.5) * 180 / math.pi # Расчет арккосинуса числа + 60.00000000000001 +math.degrees(math.pi / 6) # Перевод угла врадианах в градусы + 29.999999999999996 +math.radians(60) # Перевод угла в градусах в радианы + 1.0471975511965976 +math.exp(2) # Возведение e вопределенную степень + 7.38905609893065 +math.log(8, 2) # Вычисление логарифма сопределенным основанием + 3.0 +math.log10(1000) # Вычисление десятичногологарифма + 3.0 +math.sqrt(52) +7.211102550927978 +math.ceil(4.25) # Округление в большуюсторону + 5 +math.floor(4.25) # Округление в меньшуюсторону + 4 +``` +Вычислим значение функции с помощью библиотеки math: + +```py + 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', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_floor', '_index', '_inst', '_isfinite', '_log', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', '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.random() # Равномерно распределенное случайное число + 0.9783548583709967 +random.uniform(1,2) # Равномерно распределенное случайное число +1.0545226550104574 +random.randint(1,10) # Случайное целое число +9 +random.gauss(5,0.5) + # Нормально распределенное случайное число +3.8139508431163205 +random.choice(["samsing","iphone","xiaomi"]) +'xiaomi' +phones = ["samsing", "iphone", "xiaomi"] +random.shuffle(phones) +phones +['iphone', 'xiaomi', 'samsing'] +random.sample(phones, 2) +['samsing', 'xiaomi'] +random.betavariate(1, 2) # Случайное число сбета-распределением + 0.5112342600587575 +random.gammavariate(1, 2) # Случайное числос гамма-распределением + 0.2940579511803219 +``` +Создал список с 4 случайными значениями, подчиняющимися равномерному, нормальному, бета и гамма - рапределениям соответственно: +```py +[random.uniform(1, 5), random.gauss(2, 1), random.betavariate(1, 2), random.gammavariate(1, 2)] +[2.751759380433057, 2.241357728072516, 0.2615781219761255, 1.9620856099384534] +``` +## 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() # Время в секундах, прошедшеес 01.01.1970 +c1 + 1760875216.8018625 +c2 = time.time()-c1 # Получение времени соввода предыдущей команды +c2 + 23.937947511672974 +dat = time.gmtime() +dat +time.struct_time(tm_year=2025, tm_mon=10, tm_mday=19, tm_hour=12, tm_min=0, tm_sec=57, tm_wday=6, tm_yday=292, tm_isdst=0) +dat.tm_mon # Получение текущего месяца + 10 +dat.tm_hour # Получение текущего часа + 12 +datLocal = time.localtime() # Получение полной информации о текущем "местном" времени +datLocal +time.struct_time(tm_year=2025, tm_mon=10, tm_mday=19, tm_hour=15, tm_min=1, tm_sec=36, tm_wday=6, tm_yday=292, tm_isdst=0) + + time.asctime(datLocal) # Преобразование представления времени из кортежа в строку + 'Sun Oct 19 15:01:36 2025' + time.ctime(c1) # Преобразование времени в секундах, прошедшего с начала эпохи, в строку + 'Sun Oct 19 15:00:16 2025' + time.sleep(10) # Прерывание работы программы на заданное количество секунд + time.mktime(datLocal) # Преобразование времени из кортежа или структуры в число секунд с начала эпохи + 1760875296.0 +``` +## 7. Графические функции. +```py + import pylab + x=list(range(-3,55,4)) + t=list(range(15)) + pylab.plot(t,x) #Создание графика в оперативной памяти + [] + pylab.title('Первый график') # Добавление названия графика + Text(0.5, 1.0, 'Первый график') + pylab.xlabel('время') # Добавление названия оси абсцисс + Text(0.5, 0, 'время') + pylab.ylabel('сигнал') # Добавление названия оси ординат + Text(0, 0.5, 'сигнал') + pylab.show() #Отображение графика на экране +``` + +![alt text](pictures/{39A2FC52-D033-47D6-AE7A-2C18DFB8849C}.png) + +На одном рисунке можно отобразить несколько графиков: + +```py +X1=[12,6,8,10,7] + +X2=[5,7,9,11,13] + +pylab.plot(X1) +pylab.plot(X2) +pylab.show() + +``` + +![alt text](pictures/{B16269AB-FF3F-4D96-AFB1-CF5AF8E3C145}.png) + +Также данный модуль дает возможность строить круговые и столбиковые диаграммы и гистограммы. +```py + region=['Центр','Урал','Сибирь','Юг'] #Метки для диаграммы + naselen=[65,12,23,17] # Значения для диаграммы + pylab.pie(naselen,labels=region) #Создание диаграммы в памяти + ([, , , ], [Text(-0.191013134139045, 1.0832885038559115, 'Центр'), Text(-0.861328292412156, -0.6841882582231001, 'Урал'), Text(0.04429273995539947, -1.0991078896938387, 'Сибирь'), Text(0.9873750693480946, -0.48486129194837324, 'Юг')]) + pylab.show() #Отображение диаграммы +``` + +![alt text](pictures/{DE7F74DD-ADCD-4FD3-B072-0FE157B24F01}.png) + +```py +pylab.hist([5, 7, 8, 5, 5, 6, 6, 7, 7, 8, 9, 5], bins=4) +pylab.show() +``` + +![alt text](pictures/image.png) + +```py +cities = ['Москва', 'СПб', 'Казань', 'Сочи'] +population = [12.5, 5.4, 1.3, 0.4] +pylab.bar(cities, population) + +pylab.show() +``` +![alt text](pictures/image-1.png) + +## 8. Статистические функции из модуля statistics. + +```py + import statistics + dir(statistics) + ['Counter', 'Decimal', 'Fraction', 'LinearRegression', 'NormalDist', 'StatisticsError', '_SQRT2', '__all__', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_coerce', '_convert', '_decimal_sqrt_of_frac', '_exact_ratio', '_fail_neg', '_float_sqrt_of_frac', '_integer_sqrt_of_frac_rto', '_isfinite', '_mean_stdev', '_normal_dist_inv_cdf', '_sqrt_bit_width', '_ss', '_sum', 'bisect_left', 'bisect_right', 'correlation', 'covariance', 'defaultdict', 'erf', 'exp', 'fabs', 'fmean', 'fsum', 'geometric_mean', 'groupby', 'harmonic_mean', 'hypot', 'linear_regression', 'log', 'math', 'mean', 'median', 'median_grouped', 'median_high', 'median_low', 'mode', 'mul', 'multimode', 'namedtuple', 'numbers', 'pstdev', 'pvariance', 'quantiles', 'random', 'reduce', 'repeat', 'sqrt', 'stdev', 'sys', 'tau', 'variance'] + statistics.mean([1, 2, 3, 4, 5, 6, 7, 8, 9]) # Вычисление среднего + 5 + statistics.stdev([1, 2, 3, 4, 5, 6, 7, 8, 9]) # Вычисление среднеквадратичного отклонения + 2.7386127875258306 + statistics.median([1, 2, 3, 4, 5, 6, 7, 8]) # Вычисление медианы + 4.5 +``` +## 9. Завершение работы со средой. +Закончил сеанс работы с IDLE.