# Отчёт по Теме 4 Ходюк Максим Романович, А-01-23 ## 2. Изучение стандартных функций модуля builtins ### 2.1. Функция round Использовал функцию на следующих примерах: ``` round(123.456,1) 123.5 round(123.456,0) 123.0 ``` Как можно заметить, второй аргумент означает количество цифр в дробной части, до которой округляется число, и при введении этого аргумента результат получается типа float Если этот аргумент не задать: ``` round(123.456) 123 type(round(123.456)) ``` То число округлится до целых и будет типа int ### 2.2. Функция range Пример: ``` gg=range(76,123,9) gg range(76, 123, 9) ``` Эта инструкция создает, так называемый, «итерируемый объект» класса range. Чтобы увидеть получившуюся последовательность чисел, его надо преобразовать, например, в список, обычным способом: ``` list(gg) [76, 85, 94, 103, 112, 121] ``` Если вызвать эту функцию с одним аргументом, то создатся диапазон от 0 до заданного числа с шагом 1: ``` 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] ``` ### 2.3. Функция zip Создал обьект список с именем qq, после чего применил функцию zip к qq и ранее созданному списку gg ``` qq = ['Hodyuk','Kovalenko','Ivanov', 'Lykova'] ff=zip(gg,qq) ``` Как и в range здесь получается «итерируемый объект» класса zip, поэтому чтобы увидеть содержимое создал кортёж ``` tuple(ff) ((76, 'Hodyuk'), (85, 'Kovalenko'), (94, 'Ivanov'), (103, 'Lykova')) ``` Элементов в полученном кортеже 4, так как из аргументов функции zip меньшую длину имел список qq, равную 4 Проверил, можно ли обратиться к полученному обьекту по индексу: ``` ff[1] Traceback (most recent call last): File "", line 1, in ff[1] TypeError: 'zip' object is not subscriptable ``` К объекту zip нельзя обращаться по индексу ### 2.4. Функция eval Применил пример использования, отобразил результат(переменную dan): ``` fff=float(input('коэффициент усиления=')); dan=eval('5*fff-156') коэффициент усиления=13 dan -91.0 ``` ### 2.5 Функция exec Функция выполняет совокупность инструкций на языке Python, например: ``` exec(input('введите инструкции:')) введите инструкции:perem=-123.456;gg=round(abs(perem)+98,3) gg 221.456 ``` ### 2.6. Самостоятельное изучение других стандартных функций Применил ранее известные функции: ``` abs(dan) 91.0 pow(2,4) 16 max([1,3,6,1]) 6 min([1,16, -591, 0]) -591 sum([1,2,3,4]) 10 len(qq) 4 ``` Изучил функции divmod и map, и применил их ``` help(divmod) Help on built-in function divmod in module builtins: divmod(x, y, /) Return the tuple (x//y, x%y). Invariant: div*y + mod == x. divmod(15,4) (3, 3) divmod(17,2) (8, 1) help(map) Help on class map in module builtins: class map(object) | map(function, iterable, /, *iterables) | | Make an iterator that computes the function using arguments from | each of the iterables. Stops when the shortest iterable is exhausted. | | Methods defined here: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __iter__(self, /) | Implement iter(self). | | __next__(self, /) | Implement next(self). | | __reduce__(self, /) | Return state information for pickling. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature. map(len,qq) list(map(len,qq)) [6, 9, 6, 6] ``` ## 3. Модуль math Импортировал модуль и вывел его содержание: ``` 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', 'fma', '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', 'sumprod', 'tan', 'tanh', 'tau', 'trunc', 'ulp'] ``` Применил некоторые функции из модуля, включая factorial ``` math.factorial(5) 120 math.sin(math.pi/2) 1.0 math.acos(math.sqrt(3)/2) 0.5235987755982989 help(math.degrees) Help on built-in function degrees in module math: degrees(x, /) Convert angle x from radians to degrees. math.degrees(math.pi/2) 90.0 math.radians(90) 1.5707963267948966 math.log(15) 2.70805020110221 math.log(8,2) 3.0 math.exp math.log10(100) 2.0 math.ceil(25.181926) 26 math.floor(25.181915) 25 ``` После применения всех необходимых функций написал инструкцию для вычисления значения выражения sin(2π/7+e0.23 ) ``` math.sin((2*math.pi/7)+math.exp(0.23)) 0.8334902641414562 ``` ## 4. Модуль cmath Испортировал модуль,вывел его содержание и изучил функции вычисления корня и получения фазы комплексного числа ``` 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 Снова импортировал модуль и вывел список функций в модуле: ``` 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'] ``` Изучил функцию seed, задающую случайное начальное состояние для псевдослучайных чисел: ``` 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(случайное число с гамма-распределением). ``` random.random() 0.8415073202155561 help(random.uniform) Help on method uniform in module random: uniform(a, b) method of random.Random instance Get a random number in the range [a, b) or [a, b] depending on rounding. The mean (expected value) and variance of the random variable are: E[X] = (a + b) / 2 Var[X] = (b - a) ** 2 / 12 random.uniform(4,13) 12.083229701608595 random.randint(1,4) 1 help(random.randint) Help on method randint in module random: randint(a, b) method of random.Random instance Return random integer in range [a, b], including both end points. help(random.gauss) Help on method gauss in module random: gauss(mu=0.0, sigma=1.0) method of random.Random instance Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function. Not thread-safe without a lock around calls. random.gauss() 0.9495673914994565 random.gauss(mu=3,sigma=2) 3.7978130361127436 help(random.choice) Help on method choice in module random: choice(seq) method of random.Random instance Choose a random element from a non-empty sequence. random.choice([1,3,5,2,1,5,7,8,9]) 5 random.shuffle([1,3,5,2,1,5,7,8,9]) aa=random.shuffle([1,3,5,2,1,5,7,8,9]) aa help(random.shuffle) Help on method shuffle in module random: shuffle(x) method of random.Random instance Shuffle list x in place, and return None. aa=[1,3,5,2,1,5,7,8,9] random.shuffle(aa) aa [5, 1, 7, 5, 3, 8, 9, 1, 2] random.sample(aa,4) [1, 3, 5, 5] help(random.betavariate) Help on method betavariate in module random: betavariate(alpha, beta) method of random.Random instance Beta distribution. Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1. The mean (expected value) and variance of the random variable are: E[X] = alpha / (alpha + beta) Var[X] = alpha * beta / ((alpha + beta)**2 * (alpha + beta + 1)) random.betavariate(13,2) 0.9768043355909166 random.gammavariate(4,6) 6.383419053564046 ``` Создал список с 4 случайными значениями, подчиняющимися, соответственно, равномерному, нормальному, бета и гамма – распределениям: ``` spis=[random.uniform(4,13),random.gauss(mu=3,sigma=2),random.betavariate(13,2),random.gammavariate(4,6)] spis [8.823603554451614, 0.9688486416723059, 0.8365506057159969, 10.812180117279787] ``` ## Модуль time ``` 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'] ``` Изучил функцию time, возвращающую время в секундах, прошедшее с начала эпохи, за которое обычно принимается 1.01.1970г. ``` c1=time.time() c2=time.time()-c1 ``` Получил в переменную dat "Всемирное координатное время", и научился обращаться к компонентам получившегося объекта: ``` dat=time.gmtime() dat time.struct_time(tm_year=2025, tm_mon=10, tm_mday=13, tm_hour=7, tm_min=19, tm_sec=44, tm_wday=0, tm_yday=286, tm_isdst=0) dat.tm_mon 10 dat.tm_mday 13 dat.tm_wday 0 ``` Получил местное время функцией localtime() ``` time.localtime() time.struct_time(tm_year=2025, tm_mon=10, tm_mday=13, tm_hour=10, tm_min=21, tm_sec=49, tm_wday=0, tm_yday=286, tm_isdst=0) ``` Изучил функции из модуля time:asctime (преобразование представления времени из кортежа в строку) , ctime (преобразование времени в секундах, прошедшего с начала эпохи, в строку), sleep (прерывание работы программы на заданное время), mktime (преобразование времени из типа кортежа или struct_time в число секунд с начала эпохи). ``` help(time.asctime) Help on built-in function asctime in module time: asctime(...) asctime([tuple]) -> string Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'. When the time tuple is not present, current time as returned by localtime() is used. time.asctime(time.localtime()) 'Mon Oct 13 10:23:33 2025' help(time.ctime) Help on built-in function ctime in module time: ctime(...) ctime(seconds) -> string Convert a time in seconds since the Epoch to a string in local time. This is equivalent to asctime(localtime(seconds)). When the time tuple is not present, current time as returned by localtime() is used. time.ctime(156323) 'Fri Jan 2 22:25:23 1970' time.ctime(1) 'Thu Jan 1 03:00:01 1970' help(time.sleep) Help on built-in function sleep in module time: sleep(object, /) sleep(seconds) Delay execution for a given number of seconds. The argument may be a floating-point number for subsecond precision. time.sleep(3) time.mktime(time.localtime()) 1760340425.0 ``` Преобразование из секунд в местное время также осуществляется функцией localtime: ``` time.localtime(c1) time.struct_time(tm_year=2025, tm_mon=10, tm_mday=13, tm_hour=10, tm_min=19, tm_sec=23, tm_wday=0, tm_yday=286, tm_isdst=0) ``` ## Графические функции Импортировал модуль pylab из пакета matplotlib, после чего создал списки и научился создавать графики ``` 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() ``` Сохранил получившийся график в файле Figure0.png Рассмотрел возможность создания нескольких графиков на одном экране ``` X1=[12,6,8,10,7] X2=[5,7,9,11,13] pylab.plot(X1) [] pylab.plot(X2) [] pylab.show() ``` Сохранил в файл с названием Figure1.png Построил круговую диаграмму, сохранил результат в файл Figure2.png ``` 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() ``` Изучил функции bar и hist, результаты сохранил в файлы Figure3.png и Figure4.png соответственно ``` pylab.bar(X1,X1) pylab.show() pylab.hist(X2,bins=3) (array([2., 1., 2.]), array([ 5. , 7.66666667, 10.33333333, 13. ]), ) pylab.show() ``` ## 8.Статистика Импортировал модуль statistics и применил 3 функции из этого модуля ``` 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', '_kernel_invcdfs', '_mean_stdev', '_newton_raphson', '_normal_dist_inv_cdf', '_quartic_invcdf', '_quartic_invcdf_estimate', '_random', '_rank', '_sqrt_bit_width', '_sqrtprod', '_ss', '_sum', '_triweight_invcdf', '_triweight_invcdf_estimate', 'acos', 'asin', 'atan', 'bisect_left', 'bisect_right', 'correlation', 'cos', 'cosh', 'count', 'covariance', 'defaultdict', 'erf', 'exp', 'fabs', 'fmean', 'fsum', 'geometric_mean', 'groupby', 'harmonic_mean', 'hypot', 'isfinite', 'isinf', 'itemgetter', 'kde', 'kde_random', 'linear_regression', 'log', 'math', 'mean', 'median', 'median_grouped', 'median_high', 'median_low', 'mode', 'multimode', 'namedtuple', 'numbers', 'pi', 'pstdev', 'pvariance', 'quantiles', 'random', 'reduce', 'repeat', 'sin', 'sqrt', 'stdev', 'sumprod', 'sys', 'tan', 'tau', 'variance'] statistics.mean(X1) 8.6 statistics.correlation(X1,X2) -0.3939192985791677 statistics.covariance(X1,X2) -3.0 ```