diff --git a/TEMA4/figure1.png b/TEMA4/figure1.png new file mode 100644 index 0000000..e5e0673 Binary files /dev/null and b/TEMA4/figure1.png differ diff --git a/TEMA4/figure2.png b/TEMA4/figure2.png new file mode 100644 index 0000000..482e3d9 Binary files /dev/null and b/TEMA4/figure2.png differ diff --git a/TEMA4/figure3.png b/TEMA4/figure3.png new file mode 100644 index 0000000..884895c Binary files /dev/null and b/TEMA4/figure3.png differ diff --git a/TEMA4/figure4.png b/TEMA4/figure4.png new file mode 100644 index 0000000..816236b Binary files /dev/null and b/TEMA4/figure4.png differ diff --git a/TEMA4/task.md b/TEMA4/task.md new file mode 100644 index 0000000..39b9e21 --- /dev/null +++ b/TEMA4/task.md @@ -0,0 +1,46 @@ +Бушманов Артём Сергеевич А-01-23 + +## Задание +**Общее контрольное задание** + +Реализовать, записать в текстовый файл и проанализировать результаты последовательности инструкций, выполняющих следующие действия: + +·      Напишите и исполните единое выражение, реализующее последовательное выполнение следующих операций: вычисление фазы комплексного числа 0.2+0.8j, округление результата до двух знаков после запятой, умножение полученного значения на 20, получение кортежа из двух значений: округленное вниз значение от деления результата на 3 и остатка от этого деления. + +·      Создайте объект класса **struct****_****time** с временными параметрами для текущего московского времени. Создайте строку с текущим часом и минутами. + +·      Создайте список с элементами – названиями дней недели. Сделайте случайную выборку из этого списка с тремя днями недели. + +·      Напишите инструкцию случайного выбора числа из последовательности целых чисел от 14 до 32 с шагом 3. + +·      Сгенерируйте нормально распределенное число N с математическим ожиданием 15 и стандартным отклонением 4 и округлите его до целого значения. Создайте список с N элементами – случайно выбранными буквами латинского алфавита. + +·      Напишите инструкцию для определения временного интервала в минутах, прошедшего с момента предыдущего (из п.2) определения временных параметров. +## Выполнение +```Python +>>>import math +>>>import cmath +>>>import random +>>>divmod((round(cmath.phase(0.2 + 0.8j), 2) * 20), 3) +(8.0, 2.6000000000000014) +>>>msc_t = time.localtime() +>>>msc_t +time.struct_time(tm_year=2025, tm_mon=10, tm_mday=24, tm_hour=12, tm_min=30, tm_sec=42, tm_wday=4, tm_yday=297, tm_isdst=0) +>>>nows = str(msc_t.tm_hour) + " " + str(msc_t.tm_min) +>>>nows +'12 30' +>>>liist = ["понедельник", "вторник", "среда", "четверг", "пятница", "суббота", "воскресенье"] +>>>random.sample(liist, 3) +['четверг', 'понедельник', 'вторник'] +>>>random.choice(range(14, 33, 3)) +29 +>>>N = round(random.gauss(15,4)) +>>>N +9 +>>>spis = list('qawsedrftgyhujikol') +>>>spis = list('qawsedrftgyhujikolp') +???random.sample(spis, N) +['d', 'u', 'h', 's', 'e', 'y', 'o', 'r', 'w'] +>>>(time.mktime(time.localtime()) - time.mktime(msc_t)) / 60 +1.1666666666666667 +``` \ No newline at end of file diff --git a/TEMA4/Отчет по теме 4.md b/TEMA4/Отчет по теме 4.md new file mode 100644 index 0000000..210c739 --- /dev/null +++ b/TEMA4/Отчет по теме 4.md @@ -0,0 +1,656 @@ +# Бушманов Артём Сергеевич А-01-23 +## 1. Запуск интерактивной оболочки IDLE + +## 2. Стандартные функции + +### 2.1. Функция round – округление числа с заданной точностью +```python +>>>round(123.456,1) +123.5 +>>>type(round(123.456,1)) + +>>>round(123.456,0) +123.0 +>>>type(round(123.456,0)) + +>>>round(123.456) +123 +>>>type(round(123.456)) + +``` +Если ndigits не указан — возвращает округлённое целое число. +Если ndigits указан (даже 0) — возвращает число с плавающей точкой. +Использует банковское округление: если число посередине между двумя возможными, выбирается ближайшее чётное. + +### 2.2. Функция range – создание последовательности целых чисел с заданным шагом или, по умолчанию, с шагом 1. + +```python +>>>gg = range(76, 123, 9) +>>>list(gg) +[76, 85, 94, 103, 112, 121] +>>>range(23) +range(0, 23) +>>>type(range(23)) + +>>>list(range(0,26)) +[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] +``` +Объект range(26) будет содержать последовательность целых чисел, начиная с 0 и до 25 (так как 26 не включается). Чтобы это увидить, необходимо применить list(). range — это легковесный объект, который генерирует числа на лету, а не хранит их все в памяти, поэтому преобразование в list нужно только для просмотра. Границы диапазона: от 0 и до 23, проход с шагом 1 по умолчанию. + +### 2.3. Функция zip - создание итерируемого объекта из кортежей +Объединяет несколько последовательностей в кортежи поэлементно. +Идёт до самой короткой последовательности. +Возвращает итератор класса zip, а не список. Для вывода: list(zip(...)). +Используется для параллельной обработки нескольких списков. +```python +>>>qq = ["Bushmanov", "Podolskiy", "Terehov", "Butko"] +>>>ff = zip(gg, qq) +>>>ff + +>>>tuple(ff) +((76, 'Bushmanov'), (85, 'Podolskiy'), (94, 'Terehov'), (103, 'Butko')) +``` +Длина получившегося объекта соответствует длине меньшего объекта-параметров(длина 4 значения). +```python +>>>ff[1] +Traceback (most recent call last): + File "", line 1, in + ff[1] +TypeError: 'zip' object is not subscriptable +``` +К объекту ff нельзя обратиться по индексу из-за того что он не итерируемый, так же он является не изменяемым. + +### 2.4. Функция eval – вычисление значения выражения, корректно записанного на языке Python и представленного в виде символьной строки. +Вычисляет строку как выражение Python и возвращает результат. +Можно использовать для динамических вычислений. +Опасна: при вводе непроверенного текста может выполняться произвольный код. + +```python +>>>fff=float(input('коэффициент усиления=')); dan=eval('5*fff-156') +коэффициент усиления=55 +>>>fff +55.0 +>>>dan +119.0 +``` +### 2.5. Функция exec – чтение и выполнение объекта-аргумента функции. +```python +>>>exec(input('введите инструкции:')) +введите инструкции:perem=-123.456;gg=round(abs(perem)+98,3) +>>>gg +221.456 +``` +- Исполняет строку как инструкцию Python.Отличие от eval: не возвращает значение, может создавать переменные и функции. +- Опасна при работе с вводом пользователя. + +### 2.6. Функции abs, pow, max, min, sum, divmod, len, map. +- Функция abs(возвращение модуля): +```python +>>>x = abs(-10) +>>>x +10 +``` +- Функция pow(возведение в степень) +```python +>>>pow(2, 10) +1024 +>>>pow(4,5,10) # 4**5 = 1024, затем 1024 % 10 = 4 +4 +``` +- Функции max и min(выбор максимального и минимального значения соответственно) +```python +>>>max(40, 50, 6) +50 +>>>min(-3, 57, 30) +-3 +``` +- Функция sum(суммирование элементов) +```python +>>>sum([1,2,3,4,5]) +15 +>>>sum([1,2,3,4,5], -5) +10 +``` +- Функция divmod(возвращение кортежа из целой части и остатка от деления) +```python +>>>divmod(36, 5) +(7, 1) +``` +- Функция len(длина списка) +```python +>>>len([1,2,3,4,5,6]) +6 +``` +- Функция map ( это встроенная функция Python, которая применяет заданную функцию к каждому элементу итерируемого объекта (списка, кортежа и т.д.) и возвращает итератор с результатами.) +```python +>>>a = [10, 20, 30] +>>>a +[10, 20, 30] +>>>b = [30, 20, 10] +>>>b +[30, 20, 10] +>>>result = list(map(lambda x, y: x + y, a, b)) +>>>result +[40, 40, 40] +``` + +## 3. Функции из стандартного модуля math – совокупность разнообразных математических функций. +```python +>>>import math +>>>dir(math) +['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', '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 in module math: + +factorial(x, /) + Find x!. + + Raise a ValueError if x is negative or non-integral. + +>>>math.factorial(5) +120 +``` +Аналогичным образом изучим и попробуем применить некоторые другие функции из этого модуля: sin, acos, degrees, radians, exp, log, log10, sqrt, ceil, floor, pi. +- Функция sin - - тригонометрия в радианах. +```python +>>>help(math.sin) +Help on built-in function sin in module math: +sin(x, /) + Return the sine of x (measured in radians). +>>>math.sin(math.pi / 3) +0.8660254037844386 +``` +- Функция acos - обратные функции. +```python +>>>help(math.acos) +Help on built-in function acos in module math: +acos(x, /) + Return the arc cosine (measured in radians) of x. + + The result is between 0 and pi. +>>>math.acos(1) +0.0 +``` +- Функция degrees - перевод между градусами и радианами. +```python +>>>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 +``` +- Функция radians - перевод между градусами и радианами. +```python +>>>help(math.radians) +Help on built-in function radians in module math: + +radians(x, /) + Convert angle x from degrees to radians. +>>>math.radians(360) +6.283185307179586 +>>>math.radians(157) +2.7401669256310974 +``` +- Функция exp - e**x +```python +>>>help(math.exp) +Help on built-in function exp in module math: +exp(x, /) + Return e raised to the power of x. +>>>math.exp(3) +20.085536923187668 +>>>math.exp(5) +148.4131591025766 +``` +- Функция log - логарифм (натуральный или по базе). +```python +>>>help(math.log) +Help on built-in function log in module math: + +log(...) + log(x, [base=math.e]) + Return the logarithm of x to the given base. + + If the base not specified, returns the natural logarithm (base e) of x. +>>>math.log(10) +2.302585092994046 +>>>math.log(math.e) +1.0 +``` +- Функция log10 - десятичный логарифм. +```python +>>>help(math.log10) +Help on built-in function log10 in module math: + +log10(x, /) + Return the base 10 logarithm of x. +>>>math.log10(10) +1.0 +>>>math.log10(100) +2.0 +>>>math.log10(105) +>>>2.0211892990699383 +``` +- Функция sqrt - корень (ошибка при отрицательных). +```python +>>>help(math.sqrt) +Help on built-in function sqrt in module math: + +sqrt(x, /) + Return the square root of x. +>>>math.sqrt(16) +4.0 +>>>math.sqrt(25) +5.0 +``` +- Функция ceil(округление в большую сторону) +```python +help(math.ceil) +Help on built-in function ceil in module math: + +ceil(x, /) + Return the ceiling of x as an Integral. + + This is the smallest integer >= x. + +>>>math.ceil(4.56) +5 +>>>math.ceil(130.1) +131 +``` +- Функция floor(округление в меньшую сторону) +```python +>>>help(math.floor) +Help on built-in function floor in module math: + +floor(x, /) + Return the floor of x as an Integral. + + This is the largest integer <= x. + +>>>math.floor(99.999) +99 +``` +- Функция pi +```python +>>>math.pi +3.141592653589793 +``` + +## 4. Функции из модуля cmath – совокупность функций для работы с комплексными числами. +```python +>>>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 – совокупность функций для выполнения операций с псевдослучайными числами и выборками. +```python +>>>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.seed(x) инициализирует внутреннее состояние генератора Mersenne Twister. Однаковый seed => одна и та же последовательность псевдослучайных значений при том же порядке вызовов. +- Функци random(равномерно распределенное случайное число от 0 до 1) +```python +>>>help(random.random) +Help on built-in function random: + +random() method of random.Random instance + random() -> x in the interval [0, 1). + +>>>random.random() +0.15224090837130377 +>>>random.random() +0.8451183120672832 +>>>random.random() +0.8392090272295469 +``` + +- Функция uniform (равномерно распределенное случайное число) +```python +>>>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. + +>>>random.uniform(1, 5) +1.4822447721210175 +>>>random.uniform(1, 500) +11.101749613668387 +``` +равномерно от a до b. +- Функция gauss(нормально распределенное случайное число) +```python +>>>help(random.gauss) +Help on method gauss in module random: + +gauss(mu, sigma) 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(1, 5) +5.705708773458442 +>>>random.gauss(12, 57) +-14.33510203993609 +``` +нормально распределённое число. +- Функция randint(случайные целые числа) +```python +>>>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. + +>>>random.randint(3, 19) +4 +>>>random.randint(3, 19) +5 +``` +целое от a до b включительно. +- Функция choice (случайный выбор из совокупности) +```python +>>>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([True, "ababba", 35, 90.3, 3+5j]) +90.3 +>>>random.choice([True, "ababba", 35, 90.3, 3+5j]) +(3+5j) +``` + +- Функця shuffle (случайная перестановка элементов списка) +```python +>>>help(random.shuffle) +Help on method shuffle in module random: + +shuffle(x, random=None) method of random.Random instance + Shuffle list x in place, and return None. + + Optional argument random is a 0-argument function returning a + random float in [0.0, 1.0); if it is the default None, the + standard random.random will be used. + +>>>lst = [True, "ababba", 35, 90.3, 3+5j] +>>>random.shuffle(lst) +>>>lst +[35, 'ababba', 90.3, (3+5j), True] +``` +- Функция sample (случайный выбор подмножества элементов) +```python +>>>help(random.sample) +Help on method sample in module random: + +sample(population, k, *, counts=None) method of random.Random instance + Chooses k unique random elements from a population sequence or set. + + Returns a new list containing elements from the population while + leaving the original population unchanged. The resulting list is + in selection order so that all sub-slices will also be valid random + samples. This allows raffle winners (the sample) to be partitioned + into grand prize and second place winners (the subslices). + + Members of the population need not be hashable or unique. If the + population contains repeats, then each occurrence is a possible + selection in the sample. + + Repeated elements can be specified one at a time or with the optional + counts parameter. For example: + + sample(['red', 'blue'], counts=[4, 2], k=5) + + is equivalent to: + + sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5) + + To choose a sample from a range of integers, use range() for the + population argument. This is especially fast and space efficient + for sampling from a large population: + + sample(range(10000000), 60) + +>>>random.sample(lst, 5) +['ababba', 90.3, True, (3+5j), 35] +>>>random.sample(lst, 1) +['ababba'] +``` +- Функция betavariate(случайное число с бета-распределением) +```python +>>>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. + +>>>random.betavariate(1, 2) +0.3174347054415454 +>>>random.betavariate(1, 2) +0.17833765040946833 +``` + +- Функция gammavariate(случайное число с гамма-распределением) +```python +>>>help(random.gammavariate) +Help on method gammavariate in module random: + +gammavariate(alpha, beta) method of random.Random instance + Gamma distribution. Not the gamma function! + + Conditions on the parameters are alpha > 0 and beta > 0. + + The probability distribution function is: + + x ** (alpha - 1) * math.exp(-x / beta) + pdf(x) = -------------------------------------- + math.gamma(alpha) * beta ** alpha + +>>>random.gammavariate(2, 5) +18.174658510394487 +>>>random.gammavariate(2, 5) +29.01757536081825 +``` + +- Создание списка с 4 случайными значениями, подчиняющимися, соответственно, равномерному, нормальному, бета и гамма – распределениям и с любыми допустимыми значениями параметров этих распределений. +```python +>>>ls_r = [0] * 4 +>>>ls_r[0] = random.uniform(0, 5) +>>>ls_r[1] = random.gauss(0, 2) +>>>ls_r[2] = random.betavariate(1, 3) +>>>ls_r[3] = random.gammavariate(3, 2) +>>>ls_r +[2.1956405045678467, -2.238234699654799, 0.30508834143011926, 1.9912119529312582] +``` +## 6. Функции из модуля time – работа с календарем и со временем. +- UNIX время и текущее время +```python +>>>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 +1759739386.6377628 +>>>c2=time.time()-c1 # временной интервал в секундах, со времени ввода предыдущей инструкции +>>>c2 +26.08662247657776 +>>>dat = time.gmtime() # Эта функция возвращает, так называемое, «Всемирное координированное время» (UTC) +>>>dat.tm_mon # получение номера месяца +10 +>>>dat +time.struct_time(tm_year=2025, tm_mon=10, tm_mday=24, tm_hour=8, tm_min=57, tm_sec=30, tm_wday=0, tm_yday=279, tm_isdst=0) + +``` + +- Текущее время с учетом часового пояса +```python +>>>mestn = time.localtime() +>>>list(mestn) +[2025, 10, 24, 12, 18, 35, 0, 279, 0] +``` + +- Функция asctime (преобразование представления времени из кортежа в строку) +```python +>>>time.asctime(mestn) + +'Mon Oct 24 12:18:35 2025' +``` +- Функция ctime (преобразование времени в секундах, прошедшего с начала эпохи, в строку) +```python +>>>time.ctime() + +'Mon Oct 24 12:22:01 2025' +``` + +- Функция sleep (прерывание работы программы на заданное время) +```python +>>>time.sleep(5) +``` + +- Функция mktime (преобразование времени из типа кортежа или struct_time в число секунд с начала эпохи) +```python +>>>time.mktime(mestn) + +1759742315.0 +``` + +- Обратное преобразование из секунд в местное время +```python +>>>time.localtime(c1) + +time.struct_time(tm_year=2025, tm_mon=10, tm_mday=6, tm_hour=11, tm_min=29, tm_sec=46, tm_wday=0, tm_yday=279, tm_isdst=0) +``` + + +## 7. Графические функции + +Импортируем модули mathplotlib и pylab для построения графика. + +-Создание и отображение графика x(t): + +```python +>>>import 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) + +- Рассмотрим способ построения нескольких графиков на одном рисунке. +```python +>>>X1 = [12, 6, 8, 10, 7] +>>>X2 = [5, 7, 9, 11, 13] +>>>pylab.plot(X1) +[] +>>>pylab.plot(X2) +[] +>>>pylab.show() +``` +![График](figure1.png) + + +- Теперь изучим возможность построения круговой диаграммы. +```python +>>>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() #Отображение диаграммы +``` +![График](figure2.png) + + +- Построение гистограммы +```python +>>>pylab.show() +>>>data = [1, 2, 2, 3, 3, 3, 4, 4, 5] +>>>pylab.hist(data) +(array([1., 0., 2., 0., 0., 3., 0., 2., 0., 1.]), array([1. , 1.4, 1.8, 2.2, 2.6, 3. , 3.4, 3.8, 4.2, 4.6, 5. ]), ) +>>>pylab.title('Простая гистограмма') +Text(0.5, 1.0, 'Простая гистограмма') +>>>pylab.xlabel('Значения') +Text(0.5, 0, 'Значения') +>>>pylab.ylabel('Частота') +Text(0, 0.5, 'Частота') +>>>pylab.show() +``` + +![График](figure3.png) + + +- Построение столбиковой диаграммы +```python +>>>fruits = ["apple", "date", "apricot", "raspberry", "watermelon"] +>>>values = [13, 16, 8, 25, 6] +>>>pylab.bar(fruits, values, color='green') + +>>>pylab.show() +``` + +![График](figure4.png) + + +Все графики, диаграммы и гистограммы сохранены в папку в формате "jpg". + +## 8. Статистический модуль statistics + +```python +>>>data = [10, 20, 30, 40, 50] +>>>statistics.mean(data) # Нахождение математического ожидания +30 +>>>statistics.median(data) # Нахождение медианы +30 +>>>statistics.stdev(data) # Нахождение среднеквадратичного отклонения +15.811388300841896 +>>>statistics.variance(data) # Нахождение дисперсии +250 +>>>statistics.mode(data) # Нахождение моды +10 +``` + +## 9. Завершение работы