# Отчёт по теме 4 Криштул Александр, А-03-23. ## 1. Начало работы. Запуск интерактивнок оболочки IDLE. Открыто окно текстового редактора. ## 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 >>> (123.456, 0) 123.0 >>> type(round(123.456, 0)) >>> round(123.456) 123 >>> type(round(123.456)) ``` ### 2.2. Функция range. ```py >>> gg = range(76, 123, 9) >>> gg range(76, 123, 9) >>> list(gg) [76, 85, 94, 103, 112, 121] >>> 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. ```py >>> qq = ['Krishtul', 'Stepanishchev', 'Ogarkov', 'Markov'] >>> zip(gg, qq) >>> ff = zip(gg, qq) >>> tuple(ff) ((76, 'Krishtul'), (85, 'Stepanishchev'), (94, 'Ogarkov'), (103, 'Markov')) >>> fff = tuple(ff) >>> len(fff) 4 >>> len(gg), len(qq) (6, 4) >>> ff[0] Traceback (most recent call last): File "", line 1, in TypeError: 'zip' object is not subscriptable ``` Невозможно обратиться с указанием индекса, потому что объект является итерируемым. ### 2.4. Функция eval. ```py >>> fff=float(input('коэффициент усиления=')); dan=eval('5*fff-156') коэффициент усиления=4 >>> dan -136.0 ``` ### 2.5. Функция exec. ```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 >>> abs(-14) 14 >>> pow(2, 3) 8 >>> max(1, 2, 3) 3 >>> min(1, 2, 3) 1 >>> sum([1, 2, 3]) 6 >>> divmod(5, 3) (1, 2) >>> len(range(9)) 9 >>> r = map(lambda x: round(x) * (-1), [12.1245, 14.125234, 534.222]) >>> list(r) [-12, -14, -534] ``` ## 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', 'sumprod', 'tan', 'tanh', 'tau', 'trunc', 'ulp'] >>> help(math.factorial) Help on built-in function factorial in module math: factorial(n, /) Find n!. Raise a ValueError if x is negative or non-integral. >>> math.factorial(5) 120 ``` ### 3.1 sin. ```py >>> math.sin(90) 0.8939966636005579 ``` ### 3.2 acos. ```py >>> math.acos(0) 1.5707963267948966 ``` ### 3.3 degrees. ```py >>> math.degrees(math.pi) 180.0 ``` ### 3.4 radians. ```py >>> math.radians(180) 3.141592653589793 ``` ### 3.5 exp. ```py >>> math.exp(4) 54.598150033144236 ``` ### 3.6 log. ```py >>> math.log(10) 2.302585092994046 ``` ### 3.7 log10. ```py >>> math.log10(100) 2.0 ``` ### 3.8 sqrt. ```py >>> math.sqrt(16) 4.0 ``` ### 3.9 ceil. ```py >>> math.ceil(3.14) 4 ``` Округление верх. ### 3.10 floor. ```py >>> math.floor(3.14) 3 ``` Округление вниз. ### 3.11 pi. ```py >>> math.pi 3.141592653589793 ``` Вычисление значения функции sin((2π/7)+exp(0.23)): ```py >>> sin((2*pi/7) + exp(0.23)) 0.8334902641414562 ``` ## 4. Функции из модуля cmath, c комплексными числами. ```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'] ``` Квадратный корень комплексного числа: ```py >>> cmath.sqrt(1.2 - 0.5j) (1.118033988749895-0.22360679774997896j) ``` Функция расчёта фазы: ```py >>> 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', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'binomialvariate', '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() ``` ```py >>> random.random() # вещественное число от 0.0 до 1.0 0.9718302557719972 >>> random.uniform(5, 15) # вещественное число от 5.0 до 15.0 13.25280136669705 >>> random.randint(1, 100) # целое число от 1 до 100 67 >>> random.gauss(0, 1) # mu - среднее значение, sigma - стандартное отклонение -1.024203625286 >>> random.choice([1, 2, 3, 4]) # случайный выбор элемента из списка, кортежа, строки и т.д. 1 >>> Num = [1, 2, 3, 4] >>> random.shuffle(Num) >>> Num [4, 3, 2, 1] >>> random.sample(Num, 2) # случайный выбор двух элементов из Num [3, 1] >>> random.betavariate(2, 5) # случайное число с плавающей точкой на основе бета-распределения 0.47197929664908556 >>> random.gammavariate(2, 1) # случайное число с плавающей точкой на основе гамма-распределения 1.1397684174940441 ``` ## 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() >>> c1 1760183600.767916 >>> c2=time.time()-c1 >>> c2 40.34894275665283 >>> dat=time.gmtime() >>> dat time.struct_time(tm_year=2025, tm_mon=10, tm_mday=11, tm_hour=12, tm_min=25, tm_sec=32, tm_wday=5, tm_yday=284, tm_isdst=0) >>> dat.tm_mon 10 >>> time.asctime((2024, 12, 10, 18, 7, 14, 1, 345, 0)) #год, месяц, день, час, минута, секунда, день недели, день года, летнее время 'Tue Dec 10 18:07:14 2024' >>> time.ctime(time.time()) 'Sat Oct 11 15:27:32 2025' >>> time.mktime((2025, 12, 25, 15, 30, 0, 0, 0, 0)) 1766665800.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() # ``` Итог: ```py >>> X1=[12,6,8,10,7]; X2=[5,7,9,11,13] >>> pylab.plot(X1) [] >>> pylab.plot(X2) [] >>> pylab.show() ``` Итог: ```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() ``` Итог: ```py >>> pylab.bar(region, naselen) >>> pylab.title('Население по регионам') Text(0.5, 1.0, 'Население по регионам') >>> pylab.ylabel('Население (млн)') Text(0, 0.5, 'Население (млн)') >>> pylab.show() ``` Итог: ```py >>> pylab.hist(naselen) >>> pylab.title('Гистограмма распределения населения') >>> pylab.xlabel('Население (млн)') >>> pylab.ylabel('Частота') >>> pylab.show() ``` Итог: ## 8. Статистический модуль statistics. ```py >>> import statistics >>> numbers = [1,2,3,4,5,6,7,8,9] >>> statistics.mean(numbers) 5 >>> statistics.median(numbers) 5 >>> a = [-1,-2,-3,-4,-5,-6,-7,-8,-9] >>> statistics.correlation(numbers, a) -1.0 ```