форкнуто от main/python-labs
				
			
			Вы не можете выбрать более 25 тем
			Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
		
		
		
		
		
			
		
			
				
	
	
		
			856 строки
		
	
	
		
			26 KiB
		
	
	
	
		
			Markdown
		
	
			
		
		
	
	
			856 строки
		
	
	
		
			26 KiB
		
	
	
	
		
			Markdown
		
	
# Тема 4. Встроенные функции
 | 
						|
Выполнил : Тимошенко А.А.
 | 
						|
Проверил : Козлюк Д.А.
 | 
						|
 | 
						|
## Пункт 1
 | 
						|
```
 | 
						|
>>> import os
 | 
						|
>>> os.chdir("C:/Users/mapon/OneDrive/Рабочий стол/ПО АС/ТЕМА4")
 | 
						|
```
 | 
						|
## Пункт 2
 | 
						|
 | 
						|
Стандартные функции (модуль builtins, импортированный по умолчанию во все скрипты)
 | 
						|
 | 
						|
### Пункт 2.1
 | 
						|
 | 
						|
round() - округление с заданной точностью
 | 
						|
```
 | 
						|
>>> 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
 | 
						|
>>> type(round(123.456,1))
 | 
						|
<class 'float'>
 | 
						|
>>> round(123.456,0)
 | 
						|
123.0
 | 
						|
>>> type(round(123.456,0))
 | 
						|
<class 'float'>
 | 
						|
>>> round(123.456)
 | 
						|
123
 | 
						|
>>> type(round(123.456))
 | 
						|
<class 'int'>
 | 
						|
```
 | 
						|
Таким образом, если ndigits не указан, функция возвращает округленное целое число.
 | 
						|
Если указан, пускай даже ноль, то число с плавающей точкой.
 | 
						|
 | 
						|
 | 
						|
### Пункт 2.2
 | 
						|
 | 
						|
range() - генерация последовательности
 | 
						|
```
 | 
						|
>>> help(range)
 | 
						|
Help on class range in module builtins:
 | 
						|
 | 
						|
class range(object)
 | 
						|
 |  range(stop) -> range object
 | 
						|
 |  range(start, stop[, step]) -> range object
 | 
						|
 |  
 | 
						|
 |  Return an object that produces a sequence of integers from start (inclusive)
 | 
						|
 |  to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
 | 
						|
 |  start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
 | 
						|
 |  These are exactly the valid indices for a list of 4 elements.
 | 
						|
 |  When step is given, it specifies the increment (or decrement).
 | 
						|
 | 
						|
>>> gg=range(76,123,9)
 | 
						|
>>> gg
 | 
						|
range(76, 123, 9)
 | 
						|
```
 | 
						|
Функция возвращает итерируемый объект типа range:
 | 
						|
```
 | 
						|
>>> type(range(76,123,9))
 | 
						|
<class 'range'>
 | 
						|
```
 | 
						|
Чтобы прочитать результат, можно записать в список:
 | 
						|
```
 | 
						|
>>> list(gg)
 | 
						|
[76, 85, 94, 103, 112, 121]
 | 
						|
```
 | 
						|
### Пункт 2.3
 | 
						|
 | 
						|
zip() - создание итерируемого объекта из кортежей
 | 
						|
```
 | 
						|
>>> qq=["Тимошенко","Ходюк","Коваленко","Иванов"]
 | 
						|
>>> ff = zip (gg, qq)
 | 
						|
>>> ff
 | 
						|
<zip object at 0x00000207EA67BD80>
 | 
						|
>>> tuple(ff)
 | 
						|
((76, 'Тимошенко'), (85, 'Ходюк'), (94, 'Коваленко'), (103, 'Иванов'))
 | 
						|
```
 | 
						|
1. Длина получившегося объекта - меньшая из длин объектов-параметров. В данном случае, это 4.
 | 
						|
2. Объект класса zip не итерируемый:
 | 
						|
```
 | 
						|
>>> ff[1]
 | 
						|
Traceback (most recent call last):
 | 
						|
  File "<pyshell#14>", line 1, in <module>
 | 
						|
    ff[1]
 | 
						|
TypeError: 'zip' object is not subscriptable
 | 
						|
```
 | 
						|
3. Объект класса zip неизменяемый.
 | 
						|
 | 
						|
### Пункт 2.4
 | 
						|
 | 
						|
eval - вычисление выражения строкой
 | 
						|
```
 | 
						|
>>> help(eval)
 | 
						|
Help on built-in function eval in module builtins:
 | 
						|
 | 
						|
eval(source, globals=None, locals=None, /)
 | 
						|
    Evaluate the given source in the context of globals and locals.
 | 
						|
    
 | 
						|
    The source may be a string representing a Python expression
 | 
						|
    or a code object as returned by compile().
 | 
						|
    The globals must be a dictionary and locals can be any mapping,
 | 
						|
    defaulting to the current globals and locals.
 | 
						|
    If only globals is given, locals defaults to it.
 | 
						|
 | 
						|
>>> fff=float(input('коэффициент усиления=')); dan=eval('5*fff-156')
 | 
						|
коэффициент усиления=13
 | 
						|
>>> fff
 | 
						|
13.0
 | 
						|
>>> dan
 | 
						|
-91.0
 | 
						|
```
 | 
						|
Пояснение:
 | 
						|
    Если выражение будет записанно некорректно, будет возвращена SyntaxError.
 | 
						|
    По умолчанию eval() имеет доступ к глобальным именам.
 | 
						|
    eval() выполняет следующую последовательность действий:
 | 
						|
        Анализ последовательности символов выражения
 | 
						|
        Компилирование в байт-код
 | 
						|
        Выполнение кода
 | 
						|
        Возвращение результата
 | 
						|
 | 
						|
 | 
						|
### Пункт 2.5
 | 
						|
 | 
						|
exec - выполнение операций строкой
 | 
						|
```
 | 
						|
>>> help(exec)
 | 
						|
Help on built-in function exec in module builtins:
 | 
						|
 | 
						|
exec(source, globals=None, locals=None, /)
 | 
						|
    Execute the given source in the context of globals and locals.
 | 
						|
    
 | 
						|
    The source may be a string representing one or more Python statements
 | 
						|
    or a code object as returned by compile().
 | 
						|
    The globals must be a dictionary and locals can be any mapping,
 | 
						|
    defaulting to the current globals and locals.
 | 
						|
    If only globals is given, locals defaults to it.
 | 
						|
 | 
						|
>>> exec(input('введите инструкции:'))
 | 
						|
введите инструкции:perem=-123.456; gg=round(abs(perem)+98,3)
 | 
						|
>>> gg
 | 
						|
221.456
 | 
						|
```
 | 
						|
Пояснение:
 | 
						|
    eval используется только для вычисления выражений и возвращает результат.
 | 
						|
    exec может выполнять любой код, но не возвращает значение.
 | 
						|
 | 
						|
### Пункт 2.6
 | 
						|
 | 
						|
Возвращение модуля (abs):
 | 
						|
```
 | 
						|
>>> abs(-98)
 | 
						|
98
 | 
						|
>>> abs(5 + 4j)
 | 
						|
6.4031242374328485
 | 
						|
```
 | 
						|
Возведение в степень:
 | 
						|
```
 | 
						|
>>> help(pow)
 | 
						|
Help on built-in function pow in module builtins:
 | 
						|
pow(base, exp, mod=None)
 | 
						|
    Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
 | 
						|
    
 | 
						|
    Some types, such as ints, are able to use a more efficient algorithm when
 | 
						|
    invoked using the three argument form.
 | 
						|
 | 
						|
>>> pow(5,5)
 | 
						|
3125
 | 
						|
>>> pow(5,5,10)
 | 
						|
5
 | 
						|
```
 | 
						|
Максимальное из значений:
 | 
						|
```
 | 
						|
>>> help(max)
 | 
						|
Help on built-in function max in module builtins:
 | 
						|
 | 
						|
max(...)
 | 
						|
    max(iterable, *[, default=obj, key=func]) -> value
 | 
						|
    max(arg1, arg2, *args, *[, key=func]) -> value
 | 
						|
    With a single iterable argument, return its biggest item. The
 | 
						|
    default keyword-only argument specifies an object to return if
 | 
						|
    the provided iterable is empty.
 | 
						|
    With two or more arguments, return the largest argument.
 | 
						|
```
 | 
						|
Обычный пример использования:
 | 
						|
```
 | 
						|
>>> max(35,4,-3)
 | 
						|
35
 | 
						|
```
 | 
						|
Со списком:
 | 
						|
```
 | 
						|
>>> max([5,0,-10])
 | 
						|
5
 | 
						|
```
 | 
						|
Со словарем:
 | 
						|
```
 | 
						|
>>> max({'a': 1, 'b': 2, 'c': 3})
 | 
						|
'c'
 | 
						|
```
 | 
						|
Пояснение:
 | 
						|
    1. Видно, что выбор большего происходит из ключей
 | 
						|
    2. Видно, что среди буквенных символов больше то, которое ближе к концу алфавита
 | 
						|
 | 
						|
С разными типами:
 | 
						|
```
 | 
						|
>>> max([34,5,6, "hehe", 5+2j])
 | 
						|
Traceback (most recent call last):
 | 
						|
  File "<pyshell#60>", line 1, in <module>
 | 
						|
    max([34,5,6, "hehe", 5+2j])
 | 
						|
TypeError: '>' not supported between instances of 'str' and 'int'
 | 
						|
```
 | 
						|
Пояснение:
 | 
						|
    Видно, что внутри функции max заложен оператор сравнения, и между разными типами
 | 
						|
    он не работает.
 | 
						|
 | 
						|
Одинаковые символы разного регистра:
 | 
						|
```
 | 
						|
>>> max("b", "B")
 | 
						|
'b'
 | 
						|
```
 | 
						|
Пояснение: тут python сравнивает коды символов в unicode. у "b" это 98, а у "B" - 66.
 | 
						|
 | 
						|
Поиск минимума:
 | 
						|
 | 
						|
Нюансы аналогичны максимуму, поэтому детально расписаны не будут.
 | 
						|
 
 | 
						|
Сумма элементов:
 | 
						|
```
 | 
						|
>>> help(sum)
 | 
						|
Help on built-in function sum in module builtins:
 | 
						|
 | 
						|
sum(iterable, /, start=0)
 | 
						|
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers
 | 
						|
    When the iterable is empty, return the start value.
 | 
						|
    This function is intended specifically for use with numeric values and may
 | 
						|
    reject non-numeric types.
 | 
						|
```
 | 
						|
Просто суммирование:
 | 
						|
```
 | 
						|
>>> sum([1,2,3,4])
 | 
						|
10
 | 
						|
```
 | 
						|
Суммирование с значением, которое добавляется к сумме:
 | 
						|
```
 | 
						|
>>> sum([1,2,3,4], -5)
 | 
						|
5
 | 
						|
```
 | 
						|
Возвращение кортежа из целой части и остатка от деления:
 | 
						|
```
 | 
						|
>>> 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(14, 3)
 | 
						|
(4, 2)
 | 
						|
```
 | 
						|
Иногда результаты для отрицательных чисел могут быть неочевидны:
 | 
						|
```
 | 
						|
>>> divmod(14, -3)
 | 
						|
(-5, -1)
 | 
						|
```
 | 
						|
Длина объекта:
 | 
						|
```
 | 
						|
>>> len((1,2,3,4,10))
 | 
						|
5
 | 
						|
>>> len("kukukukukuku")
 | 
						|
12
 | 
						|
>>> len(["kukukukukkuuk","kuku"])
 | 
						|
2
 | 
						|
>>> len({'a': 1, 'b': 2, 'c': 3})
 | 
						|
3
 | 
						|
```
 | 
						|
Но при этом:
 | 
						|
```
 | 
						|
>>> len(43)
 | 
						|
Traceback (most recent call last):
 | 
						|
  File "<pyshell#90>", line 1, in <module>
 | 
						|
    len(43)
 | 
						|
TypeError: object of type 'int' has no len()
 | 
						|
```
 | 
						|
Применение функции к каждому элементу коллекции:
 | 
						|
```
 | 
						|
>>> help(map)
 | 
						|
Help on class map in module builtins:
 | 
						|
class map(object)
 | 
						|
 |  map(func, *iterables) --> map object
 | 
						|
 |  
 | 
						|
 |  Make an iterator that computes the function using arguments from
 | 
						|
 |  each of the iterables.  Stops when the shortest iterable is exhausted.
 | 
						|
```
 | 
						|
Пример:
 | 
						|
```
 | 
						|
>>> map(int, ["1", "14"])
 | 
						|
<map object at 0x00000158BF19F250>
 | 
						|
>>> list(map(int, ["1", "14"]))
 | 
						|
[1, 14]
 | 
						|
```
 | 
						|
Как следует из справки, если сообщается несколько коллекций, map закончится, когда применит
 | 
						|
функцию к самой короткой из них.
 | 
						|
 | 
						|
## Пункт 3
 | 
						|
 | 
						|
Стандартный модуль math
 | 
						|
```
 | 
						|
>>> 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
 | 
						|
```
 | 
						|
Нахождение синуса:
 | 
						|
```
 | 
						|
>>> help(math.sin)
 | 
						|
Help on built-in function sin in module math:
 | 
						|
sin(x, /)
 | 
						|
    Return the sine of x (measured in radians).
 | 
						|
 | 
						|
>>> math.sin(3.141)
 | 
						|
0.0005926535550994539
 | 
						|
>>> math.sin(-1)
 | 
						|
-0.8414709848078965
 | 
						|
```
 | 
						|
Нахождение арккосинуса:
 | 
						|
```
 | 
						|
>>> math.acos(1)
 | 
						|
0.0
 | 
						|
>>> math.acos(11)
 | 
						|
Traceback (most recent call last):
 | 
						|
  File "<pyshell#120>", line 1, in <module>
 | 
						|
    math.acos(11)
 | 
						|
ValueError: math domain error
 | 
						|
 | 
						|
>>> math.acos(-1)
 | 
						|
3.141592653589793
 | 
						|
```
 | 
						|
Перевод из радиан в градусы:
 | 
						|
```
 | 
						|
>>> help(math.degrees)
 | 
						|
Help on built-in function degrees in module math:
 | 
						|
degrees(x, /)
 | 
						|
    Convert angle x from radians to degrees.
 | 
						|
 | 
						|
>>> math.degrees(6.28)
 | 
						|
359.817495342157
 | 
						|
 | 
						|
>>> math.degrees(1)
 | 
						|
57.29577951308232
 | 
						|
```
 | 
						|
Перевод из градусов в радианы:
 | 
						|
```
 | 
						|
>>> 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(90)
 | 
						|
1.5707963267948966
 | 
						|
>>> math.radians(57)
 | 
						|
0.9948376736367679
 | 
						|
>>> math.radians(3.1415)
 | 
						|
0.05482951845140187
 | 
						|
```
 | 
						|
Число е в степени заданного:
 | 
						|
```
 | 
						|
>>> help(math.exp)
 | 
						|
Help on built-in function exp in module math:
 | 
						|
exp(x, /)
 | 
						|
    Return e raised to the power of x.
 | 
						|
    
 | 
						|
>>> math.exp(0)
 | 
						|
1.0
 | 
						|
>>> math.exp(1)
 | 
						|
2.718281828459045
 | 
						|
>>> math.exp(-5)
 | 
						|
0.006737946999085467
 | 
						|
```
 | 
						|
Нахождение логарифма:
 | 
						|
```
 | 
						|
>>> 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(math.e)
 | 
						|
1.0
 | 
						|
>>> math.log(5)
 | 
						|
1.6094379124341003
 | 
						|
>>> math.log(25,5)
 | 
						|
2.0
 | 
						|
```
 | 
						|
Согласно нормам математики, логарифмируемое выражение и основание логарифма не могут быть
 | 
						|
отрицательными. Это есть и в python, попытка задать такие значения вернет ValueError.
 | 
						|
 | 
						|
Десятичный логарифм:
 | 
						|
```
 | 
						|
>>> math.log10(0.0001)
 | 
						|
-4.0
 | 
						|
>>> math.log10(10000)
 | 
						|
4.0
 | 
						|
```
 | 
						|
Извлечение квадратного корня:
 | 
						|
```
 | 
						|
>>> math.sqrt(49)
 | 
						|
7.0
 | 
						|
```
 | 
						|
В данном случае, в отличие от канонов матанализа, задание отрицательного аргумента вернет
 | 
						|
ValueError, а не комплексное число.
 | 
						|
 | 
						|
Округление числа до ближайшего целого вверх:
 | 
						|
```
 | 
						|
>>> 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(5.77)
 | 
						|
6
 | 
						|
>>> math.ceil(6.00001)
 | 
						|
7
 | 
						|
>>> math.ceil(-6.7)
 | 
						|
-6
 | 
						|
>>> math.ceil(-6)
 | 
						|
-6
 | 
						|
```
 | 
						|
Округление вниз:
 | 
						|
```
 | 
						|
>>> math.floor(7.99)
 | 
						|
7
 | 
						|
>>> math.floor(-3.7)
 | 
						|
-4
 | 
						|
```
 | 
						|
Константа: число пи:
 | 
						|
```
 | 
						|
>>> math.pi
 | 
						|
3.141592653589793
 | 
						|
```
 | 
						|
Пример комбинированного использования:
 | 
						|
```
 | 
						|
>>> 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', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__',
 | 
						|
 '__file__', '__loader__', '__name__', '__package__', '__spec__', '_accumulate', '_acos',
 | 
						|
 '_bisect', '_ceil', '_cos', '_e', '_exp', '_floor', '_inst', '_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() вызывает time.time(), а эта функция, в свою очередь,
 | 
						|
возвращает время в Unix-формате. То есть в качестве сида используется текущее время.
 | 
						|
 | 
						|
Случайное число от 0 до 1:
 | 
						|
```
 | 
						|
>>> 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.009279717292968392
 | 
						|
>>> random.random()
 | 
						|
0.8044346046065457
 | 
						|
>>> random.random()
 | 
						|
0.2928444484701447
 | 
						|
```
 | 
						|
Равномерно распределенное случайное число:
 | 
						|
```
 | 
						|
>>> 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(2,5)
 | 
						|
4.803201121309196
 | 
						|
```
 | 
						|
Равномерное случайное целое:
 | 
						|
```
 | 
						|
>>> 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,18)
 | 
						|
5
 | 
						|
>>> random.randint(3,18)
 | 
						|
13
 | 
						|
```
 | 
						|
Случайное из коллекции:
 | 
						|
```
 | 
						|
>>> 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.
 | 
						|
```
 | 
						|
Вернет IndexError, если коллекция пустая.
 | 
						|
```
 | 
						|
>>> random.choice([False, "hehehe", 67, 90.7, 5+8j])
 | 
						|
90.7
 | 
						|
```
 | 
						|
Случайное перемешивание элементов коллекции:
 | 
						|
```
 | 
						|
>>> 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 = [False, "hehehe", 67, 90.7, 5+8j]
 | 
						|
>>> random.shuffle(lst)
 | 
						|
>>> lst
 | 
						|
[67, False, 90.7, (5+8j), 'hehehe']
 | 
						|
```
 | 
						|
Возвращает None, изменяет исходный объект. Работает только с изменяемами типами.
 | 
						|
 | 
						|
Нормально распределенное случайное число:
 | 
						|
```
 | 
						|
>>> 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.
 | 
						|
```
 | 
						|
Без заданных матожидания и дисперсии, в отличие, например, от R, возвращает TypeError, а не
 | 
						|
берет 0 и 1 как значения по умолчанию.
 | 
						|
```
 | 
						|
>>> random.gauss(0,1)
 | 
						|
1.1859475053515318
 | 
						|
```
 | 
						|
Случайное подмножество:
 | 
						|
```
 | 
						|
>>> 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.  <...>
 | 
						|
 | 
						|
>>> random.sample(lst, 5)
 | 
						|
['cherry', 'tangerine', 'banana', 'pineapple', 'peach']
 | 
						|
>>> random.sample(lst, 1)
 | 
						|
['tangerine']
 | 
						|
>>> random.sample(lst, 0)
 | 
						|
[]
 | 
						|
```
 | 
						|
Поставить как k число большее, чем длина коллекции, нельзя (TypeError)
 | 
						|
 | 
						|
Случайное число, подчиняющееся бета-распределению:
 | 
						|
```
 | 
						|
>>> 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.4074810441922475
 | 
						|
```
 | 
						|
Случайное число, подчиняющееся гамма-распределению:
 | 
						|
```
 | 
						|
>>> 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,4)
 | 
						|
1.9359228890418254
 | 
						|
```
 | 
						|
Список из четырех чисел с разными законами распределения:
 | 
						|
```
 | 
						|
>>> rl = [0] * 4
 | 
						|
>>> rl[0] = random.uniform(2,6)
 | 
						|
>>> rl[1] = random.gauss(2, 0.5)
 | 
						|
>>> rl[2] = random.betavariate(2,6)
 | 
						|
>>> rl[3] = random.gammavariate(2,6)
 | 
						|
>>> rl
 | 
						|
[2.6190336401985204, 1.82010731374589, 0.18732603571429413, 20.348843073887398]
 | 
						|
```
 | 
						|
## Пункт 6
 | 
						|
```
 | 
						|
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']
 | 
						|
```
 | 
						|
UNIX-время:
 | 
						|
```
 | 
						|
>>> c1 = time.time()
 | 
						|
>>> c1
 | 
						|
1758971496.5712385
 | 
						|
>>> c2=time.time()-c1
 | 
						|
>>> c2
 | 
						|
8.266037702560425
 | 
						|
```
 | 
						|
Возвращается время в секундах с начала эпохи UNIX: 00:00:00 UTC 1 января 1970 года.
 | 
						|
 | 
						|
Текущее время:
 | 
						|
```
 | 
						|
>>> time.gmtime
 | 
						|
<built-in function gmtime>
 | 
						|
 | 
						|
>>> help(time.gmtime)
 | 
						|
Help on built-in function gmtime in module time:
 | 
						|
 | 
						|
gmtime(...)
 | 
						|
    gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,
 | 
						|
                           tm_sec, tm_wday, tm_yday, tm_isdst)
 | 
						|
 | 
						|
    Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
 | 
						|
    GMT).  When 'seconds' is not passed in, convert the current time instead.
 | 
						|
 | 
						|
    If the platform supports the tm_gmtoff and tm_zone, they are available as
 | 
						|
    attributes only.>>> dat=time.gmtime()
 | 
						|
 | 
						|
>>> dat=time.gmtime()
 | 
						|
>>> list(dat)
 | 
						|
[2025, 9, 27, 11, 12, 18, 5, 270, 0]
 | 
						|
>>> dat.tm_mon
 | 
						|
9
 | 
						|
>>> dat.tm_year
 | 
						|
2025
 | 
						|
>>> dat.tm_yday
 | 
						|
270
 | 
						|
>>> dat.tm_isdst #Показывает, действует ли летнее время (0 - нет, 1 - да, -1 - нет данных)
 | 
						|
0
 | 
						|
```
 | 
						|
Текущее время с учетом часового пояса:
 | 
						|
```
 | 
						|
>>> here = time.localtime()
 | 
						|
>>> list(here)
 | 
						|
[2025, 9, 27, 14, 16, 28, 5, 270, 0]
 | 
						|
```
 | 
						|
Время из кортежа в строку:
 | 
						|
```
 | 
						|
>>> time.asctime(here)
 | 
						|
'Sat Sep 27 14:16:28 2025'
 | 
						|
```
 | 
						|
Время из секунд в строку:
 | 
						|
```
 | 
						|
>>> time.ctime()
 | 
						|
'Sat Sep 27 14:17:07 2025'
 | 
						|
```
 | 
						|
Пауза:
 | 
						|
```
 | 
						|
>>> time.sleep(5)
 | 
						|
```
 | 
						|
Из кортежа в секунды с начала эпохи:
 | 
						|
```
 | 
						|
>>> time.mktime(here)
 | 
						|
1758971788.0
 | 
						|
```
 | 
						|
## Пункт 7
 | 
						|
```
 | 
						|
Графические функции модуля pylab пакета matplotlib
 | 
						|
 | 
						|
>>> import matplotlib
 | 
						|
>>> import pylab
 | 
						|
 | 
						|
>>> x=list(range(-3,55,4))
 | 
						|
>>> t=list(range(15))
 | 
						|
 | 
						|
>>> pylab.plot(t,x)  #Создание графика в оперативной памяти
 | 
						|
[<matplotlib.lines.Line2D object at 0x00000158D9921670>]
 | 
						|
 | 
						|
>>> pylab.title('Первый график')
 | 
						|
Text(0.5, 1.0, 'Первый график')
 | 
						|
 | 
						|
>>> pylab.xlabel('время')
 | 
						|
Text(0.5, 0, 'время')
 | 
						|
>>> pylab.ylabel('сигнал')
 | 
						|
Text(0, 0.5, 'сигнал')
 | 
						|
 | 
						|
>>> pylab.show()
 | 
						|
```
 | 
						|
Открылось внешнее окно с графиком. Файл сохранен с именем Ris1
 | 
						|
 | 
						|
Два графика на одном окне:
 | 
						|
```
 | 
						|
>>> X1=[12,6,8,10,7]
 | 
						|
>>> X2=[5,7,9,11,13]
 | 
						|
>>> pylab.plot(X1)
 | 
						|
[<matplotlib.lines.Line2D object at 0x00000158D9AEB130>]
 | 
						|
>>> pylab.plot(X2)
 | 
						|
[<matplotlib.lines.Line2D object at 0x00000158D9AEB3D0>]
 | 
						|
>>> pylab.show()
 | 
						|
```
 | 
						|
Появились две ломаные линии синего и оранжевого цвета.
 | 
						|
 | 
						|
Круговая диаграмма:
 | 
						|
```
 | 
						|
>>> region=['Центр','Урал','Сибирь','Юг']
 | 
						|
>>> naselen=[65,12,23,17]
 | 
						|
>>> naselen=[65,12,23,17]
 | 
						|
([<matplotlib.patches.Wedge object at 0x00000158DBCC8820>, <matplotlib.patches.Wedge object at 0x00000158DBCC8760>, <matplotlib.patches.Wedge object at 0x00000158DBCC8FD0>, <matplotlib.patches.Wedge object at 0x00000158DBCDE490>], [Text(-0.1910130855889933, 1.083288512416601, 'Центр'), Text(-0.8613283319035216, -0.6841882085072037, 'Урал'), Text(0.04429273729355889, -1.0991078898011077, 'Сибирь'), Text(0.9873752043868569, -0.4848610169543564, 'Юг')])
 | 
						|
>>> pylab.show()
 | 
						|
```
 | 
						|
Сохранено в Ris2
 | 
						|
 | 
						|
Столбиковая диаграмма:
 | 
						|
```
 | 
						|
>>> fruits = ["apple", "date", "apricot", "raspberry", "watermelon"]
 | 
						|
>>> values = [10, 15, 7, 20, 3]
 | 
						|
>>> pylab.bar(fruits, values, color='skyblue')
 | 
						|
<BarContainer object of 5 artists>
 | 
						|
>>> pylab.show()
 | 
						|
```
 | 
						|
Сохранено в Ris4
 | 
						|
 | 
						|
## Пункт 8
 | 
						|
 | 
						|
Статистический модуль statistics
 | 
						|
```
 | 
						|
>>> dir(s)
 | 
						|
['Counter', 'Decimal', 'Fraction', 'NormalDist', 'StatisticsError', '__all__',
 | 
						|
 '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
 | 
						|
 '__package__', '__spec__', '_coerce', '_convert', '_exact_ratio', '_fail_neg',
 | 
						|
 '_find_lteq', '_find_rteq', '_isfinite', '_normal_dist_inv_cdf', '_ss', '_sum',
 | 
						|
 'bisect_left', 'bisect_right', 'erf', 'exp', 'fabs', 'fmean', 'fsum', 'geometric_mean',
 | 
						|
 'groupby', 'harmonic_mean', 'hypot', 'itemgetter', 'log', 'math', 'mean', 'median',
 | 
						|
 'median_grouped', 'median_high', 'median_low', 'mode', 'multimode', 'numbers', 'pstdev',
 | 
						|
 'pvariance', 'quantiles', 'random', 'sqrt', 'stdev', 'tau', 'variance']
 | 
						|
```
 | 
						|
Математическое ожидание:
 | 
						|
```
 | 
						|
>>> data = [10, 20, 30, 40, 50]
 | 
						|
>>> statistics.mean(data)
 | 
						|
30
 | 
						|
```
 | 
						|
Если объект пустой, вернет StatisticsError
 | 
						|
 | 
						|
Медиана:
 | 
						|
```
 | 
						|
>>> statistics.median(data)
 | 
						|
30
 | 
						|
```
 | 
						|
Среднеквадратичное отклонение:
 | 
						|
```
 | 
						|
>>> statistics.stdev(data)
 | 
						|
15.811388300841896
 | 
						|
```
 | 
						|
Среднее можно сообщить самостоятельно: stdev(data, xbar=None)
 | 
						|
 | 
						|
Дисперсия:
 | 
						|
```
 | 
						|
>>> statistics.variance(data)
 | 
						|
250
 | 
						|
```
 | 
						|
Квантили:
 | 
						|
```
 | 
						|
>>> data = [10, 56, 73, 7, 20, 30, 40, 50, 56, 77, 3]
 | 
						|
>>> statistics.quantiles(data)
 | 
						|
[10.0, 40.0, 56.0]
 | 
						|
```
 | 
						|
По умолчанию n = 4, это квартили. Можно указать 100, например, для процентилей.
 | 
						|
 | 
						|
 |