форкнуто от main/python-labs
main
Родитель
fa60788940
Сommit
d988fc8b25
@ -0,0 +1,748 @@
|
||||
### Отчет тема 4
|
||||
##Пункт 2 Стандартные функции (модуль builtins, импортированный по умолчанию)
|
||||
##Пункт 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.
|
||||
```
|
||||
```py
|
||||
>>> round(123.456,1)
|
||||
123.5
|
||||
>>> type(round(123.456,1))
|
||||
<class 'float'>
|
||||
```
|
||||
```py
|
||||
>>> round(123.456,0)
|
||||
123.0
|
||||
>>> type(round(123.456,0))
|
||||
<class 'float'>
|
||||
```
|
||||
```py
|
||||
>>> round(123.456)
|
||||
123
|
||||
>>> type(round(123.456))
|
||||
<class 'int'>
|
||||
```
|
||||
Если ndigits не указан, функция возвращает округленное целое число.
|
||||
Если указано, то число с плавающей точкой
|
||||
|
||||
##Пункт 2.2
|
||||
Функция range создание последовательности целых чисел с заданным шагом или, по умолчанию, с шагом 1.
|
||||
```py
|
||||
>>> gg=range(76,123,9)
|
||||
>>> gg
|
||||
range(76, 123, 9)
|
||||
>>> type(gg)
|
||||
<class 'range'>
|
||||
>>> list(gg)
|
||||
[76, 85, 94, 103, 112, 121]
|
||||
```
|
||||
Можно и не задавать шаг
|
||||
```py
|
||||
>>> 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 – создание общего объекта, элементами которого являются кортежи, составленные из эле-ментов двух или более объектов-последовательностей
|
||||
```py
|
||||
>>> qq = ['Цветкова', 'Снегура','Зеленкина']
|
||||
>>> ff=zip(gg,qq)
|
||||
>>> ff
|
||||
<zip object at 0x000001903C06A5C0>
|
||||
>>> tuple(ff)
|
||||
((76, 'Цветкова'), (85, 'Снегура'), (94, 'Зеленкина'))
|
||||
>>> ff[0]
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
TypeError: 'zip' object is not subscriptable
|
||||
```
|
||||
```py
|
||||
>>> ff[1]
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#34>", line 1, in <module>
|
||||
ff[1]
|
||||
TypeError: 'zip' object is not subscriptable
|
||||
```
|
||||
Объект класса zip неизменяемый.
|
||||
|
||||
##Пункт 2.4. Функция eval – вычисление значения выражения, корректно записанного на языке Python и представленного в виде символьной строки.
|
||||
```py
|
||||
>>> fff=float(input('коэффициент усиления=')); dan=eval('5*fff-156')
|
||||
коэффициент усиления=5
|
||||
>>> dan
|
||||
-131.0
|
||||
>>> fff
|
||||
5.0
|
||||
```
|
||||
eval() — Это встроенная функция в Python, которая выполняет строку кода как программу.
|
||||
Как работает:
|
||||
1)Компилирует строку в байт-код
|
||||
2)Выполняет этот байт-код в заданном контексте
|
||||
##Пункт 2.5. Похожая на eval функция exec – чтение и выполнение объекта-аргумента функции. Этот объ-ект должен представлять собой строку символов с совокупностью инструкций на языке Python.
|
||||
```py
|
||||
>>> exec(input('введите инструкции:'))
|
||||
введите инструкции:perem=-123.456;gg=round(abs(perem)+98,3)
|
||||
>>> gg
|
||||
221.456
|
||||
Пояснение:
|
||||
eval превращает текст в работающий код
|
||||
exec может выполнять любой код, но не возвращает значение.
|
||||
##Пункт 2.6. Самостоятельно изучите и попробуйте применить функции abs, pow, max, min, sum, divmod, len, map.
|
||||
```py
|
||||
Возведение модуля (abs)
|
||||
```py
|
||||
>>> abs(-5)
|
||||
5
|
||||
>>> abs(5+5j)
|
||||
7.0710678118654755
|
||||
>>> abs(4**(-10))
|
||||
9.5367431640625e-07
|
||||
>>> abs(-4**10)
|
||||
1048576
|
||||
>>> abs(-4**(-10))
|
||||
9.5367431640625e-07
|
||||
```
|
||||
Возведение степени
|
||||
```py
|
||||
>>> pow(5,2)
|
||||
25
|
||||
>>> pow(-5,-2)
|
||||
0.04
|
||||
>>> pow(5,4,2)
|
||||
1
|
||||
>>> pow(5+5j,2)
|
||||
50j
|
||||
```
|
||||
Максимальное значение
|
||||
|
||||
```py
|
||||
>>> max(2,5.8,7)
|
||||
7
|
||||
>>> max([4,0,-7])
|
||||
4
|
||||
>>> max({'a': 1, 'b': 2, 'c': 3}) #выбор большего происходит из ключей
|
||||
'c'
|
||||
>>> max(["ee", "eee", "eeeeeee"], key = len)
|
||||
'eeeeeee'
|
||||
>>> max("b", "B") #сравнивает коды символов в unicode
|
||||
'b'
|
||||
>>> max([34,5,6, "e", 5+2j])
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
TypeError: '>' not supported between instances of 'str' and 'int'
|
||||
```
|
||||
Видно что с разными типами данных не работает
|
||||
|
||||
Минимальное значение
|
||||
```py
|
||||
>>> min(2,5.8,7)
|
||||
2
|
||||
>>> min(({'a': 1, 'b': 2, 'c': 3})) #по ключу
|
||||
'a'
|
||||
>>> min(-7,-6,abs(-8))
|
||||
-7
|
||||
```
|
||||
Сумма элементов
|
||||
```py
|
||||
>>> sum([1,2,3,4])
|
||||
10
|
||||
>>> sum([1,2,3,4], -2)
|
||||
8
|
||||
```
|
||||
```py
|
||||
>>> sum("bbbb", "аааа")
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
TypeError: sum() can't sum strings [use ''.join(seq) instead]
|
||||
>>> sum(5+5j,3)
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
TypeError: 'complex' object is not iterable
|
||||
>>> sum(5+5j,5+5j)
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
TypeError: 'complex' object is not iterable
|
||||
>>> sum(4.5,5)
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
TypeError: 'float' object is not iterable
|
||||
>>> sum(4.5,4.5)
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
TypeError: 'float' object is not iterable
|
||||
```
|
||||
Возвращение кортежа из целой части и остатка от деления
|
||||
```py
|
||||
>>> 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(20,3)
|
||||
(6, 2) #20 // 3 = 6 (целая часть) 20 % 3 = 2 (остаток)
|
||||
>>> divmod(20,-3)
|
||||
(-7, -1) 20 ÷ (-3) = -6.666... округляем вниз -7 20 % -3 = 1
|
||||
```
|
||||
|
||||
Длина объекта
|
||||
```py
|
||||
>>> len((1,2,2))
|
||||
3
|
||||
>>> len("aaaaaaaaaa")
|
||||
10
|
||||
>>> len(["aaaa","ddddddddddd"])
|
||||
2
|
||||
>>> len({'a': 1, 'b': 2, 'c': 3})
|
||||
3
|
||||
>>> len(12)
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
TypeError: object of type 'int' has no len()
|
||||
```
|
||||
Применение функции к каждому элементу коллекции
|
||||
```py
|
||||
>>> 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", "2"])
|
||||
<map object at 0x000001903C2BB5E0>
|
||||
>>> list(map(int, ["1", "2"]))
|
||||
[1, 2]
|
||||
```
|
||||
Останавливается когда самая короткая коллекция заканчивается
|
||||
"Лишние" элементы из более длинных коллекций игнорируются
|
||||
|
||||
## Пункт 3 Стандартный модуль math
|
||||
```py
|
||||
>>> 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
|
||||
```
|
||||
Нахождение синуса
|
||||
```py
|
||||
>>> 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/2)
|
||||
1.0
|
||||
>>> math.sin(0.96)
|
||||
0.8191915683009983
|
||||
```
|
||||
Нахождение арккосинуса
|
||||
```py
|
||||
>>> math.acos(1)
|
||||
0.0
|
||||
>>> math.acos(-1)
|
||||
3.141592653589793
|
||||
>>> math.acos(-0.54)
|
||||
2.1412334361948187
|
||||
>>> math.acos(5) #больше 1 нельзя
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: math domain error
|
||||
```
|
||||
Перевод из радиан в градусы
|
||||
```py
|
||||
>>> help(math.degrees)
|
||||
Help on built-in function degrees in module math:
|
||||
|
||||
degrees(x, /)
|
||||
Convert angle x from radians to degrees.
|
||||
|
||||
>>> math.radians(math.pi)
|
||||
0.05483113556160755
|
||||
|
||||
>>> math.radians(360)
|
||||
6.283185307179586
|
||||
|
||||
>>> math.radians(90)
|
||||
1.5707963267948966
|
||||
```
|
||||
|
||||
Число е в степени заданного
|
||||
```py
|
||||
>>> 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
|
||||
>>> math.exp(1/2)
|
||||
1.6487212707001282
|
||||
```
|
||||
Нахождение логарифма
|
||||
```py
|
||||
>>> 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
|
||||
>>> math.log(-25,5) #с отрицательными числами не работает
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: math domain error
|
||||
>>> math.log(25,-5)
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: math domain error
|
||||
```
|
||||
Десятичный логарифм
|
||||
```py
|
||||
>>> math.log10(10)
|
||||
1.0
|
||||
>>> math.log10(0.01)
|
||||
-2.0
|
||||
```
|
||||
Извлечение квадратного корня
|
||||
```py
|
||||
>>> math.sqrt(25)
|
||||
5.0
|
||||
>>> math.sqrt(26)
|
||||
5.0990195135927845
|
||||
>>> math.sqrt(26.7)
|
||||
5.167204273105526
|
||||
>>> math.sqrt(-25)
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
ValueError: math domain error
|
||||
>>> math.sqrt(26.7+7j)
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
TypeError: must be real number, not complex
|
||||
```
|
||||
Округление числа до ближайшего целого вверх
|
||||
```py
|
||||
>>> 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(1.2)
|
||||
2
|
||||
>>> math.ceil(9.99)
|
||||
10
|
||||
>>> math.ceil(-6.2)
|
||||
-6
|
||||
>>> math.ceil(-6.9)
|
||||
-6
|
||||
```
|
||||
Округление вниз
|
||||
```py
|
||||
>>> math.floor(1.2)
|
||||
1
|
||||
>>> math.floor(9.99)
|
||||
9
|
||||
>>> math.floor(-6.2)
|
||||
-7
|
||||
>>> math.floor(-6.9)
|
||||
-7
|
||||
>>> math.floor(-6.9+5j)
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
TypeError: must be real number, not complex
|
||||
```
|
||||
Константа: число пи
|
||||
```py
|
||||
>>> math.pi
|
||||
3.141592653589793
|
||||
```
|
||||
комбинированное использование
|
||||
```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()
|
||||
```
|
||||
```py
|
||||
>>> help(random.random)
|
||||
Help on built-in function random:
|
||||
|
||||
random() method of random.Random instance
|
||||
random() -> x in the interval [0, 1).
|
||||
```
|
||||
Случайное число от 0 до 1
|
||||
```py
|
||||
>>> random.random()
|
||||
0.23002075073724337
|
||||
>>> random.random()
|
||||
0.535712008113208
|
||||
>>> random.random()
|
||||
0.4738049347613569
|
||||
>>> 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.
|
||||
```
|
||||
Равномерно распределенное случайное число
|
||||
```py
|
||||
>>> random.uniform(20,30)
|
||||
22.41214721441803
|
||||
```
|
||||
Равномерное случайное целое
|
||||
```py
|
||||
>>> 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(20,30)
|
||||
21
|
||||
>>> random.randint(20,30)
|
||||
27
|
||||
```
|
||||
Случайное из коллекции
|
||||
```py
|
||||
>>> 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([ъъъ, "уууууууe", 80, 7, 5+5j])
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
NameError: name 'ъъъ' is not defined
|
||||
>>> random.choice(["ffff", "уууууууe", 80, 7, 5+5j])
|
||||
80
|
||||
>>> random.choice(["ffff", "уууууууe", 80, 7, 5+5j])
|
||||
(5+5j)
|
||||
```
|
||||
|
||||
Нормально распределенное случайное число
|
||||
```py
|
||||
>>> 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,1)
|
||||
-0.43812614222540897
|
||||
>>> random.gauss(7,8)
|
||||
11.287669776968896
|
||||
```
|
||||
Случайное подмножество
|
||||
```py
|
||||
>>> 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.
|
||||
|
||||
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)
|
||||
|
||||
>>> lst=('a','b','c')
|
||||
>>> random.sample(lst, 2)
|
||||
['a', 'c']
|
||||
>>> random.sample(lst, 0)
|
||||
[]
|
||||
>>> random.sample(list, 7)
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\Lib\random.py", line 439, in sample
|
||||
raise TypeError("Population must be a sequence. "
|
||||
TypeError: Population must be a sequence. For dicts or sets, use sorted(d).
|
||||
```
|
||||
Случайное число, подчиняющееся бета-распределению
|
||||
```py
|
||||
>>> 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(3,4)
|
||||
0.4104754948305531
|
||||
>>> random.betavariate(3,4)
|
||||
0.4104754948305531
|
||||
```
|
||||
Случайное число, подчиняющееся гамма-распределению
|
||||
```py
|
||||
>>> 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(3,4)
|
||||
18.75253913135498
|
||||
```
|
||||
Список из четырех чисел с разными законами распределения:
|
||||
```py
|
||||
>>> rd=[random.uniform(3,4),random.gauss(3,4),random.betavariate(3,4),random.gammavariate(3,4)]
|
||||
>>> rd
|
||||
[3.9065412706472173, 5.093585831129117, 0.423027969366889, 7.115102862880251]
|
||||
```
|
||||
## Пункт 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']
|
||||
```
|
||||
UNIX-время
|
||||
```py
|
||||
>>> c1=time.time()
|
||||
>>> c1
|
||||
1760272978.995956
|
||||
>>> c2=time.time()-c1
|
||||
>>> c2
|
||||
12.162038326263428
|
||||
```
|
||||
Текущее время
|
||||
```py
|
||||
>>> 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()
|
||||
>>> list(dat)
|
||||
[2025, 10, 12, 12, 44, 15, 6, 285, 0]
|
||||
>>> dat.tm_year
|
||||
2025
|
||||
>>> dat.tm_yday
|
||||
285
|
||||
>>> dat.tm_isdst #Показывает, действует ли летнее время (0 - нет, 1 - да, -1 - нет данных)
|
||||
0
|
||||
```
|
||||
Текущее время с учетом часового пояса
|
||||
```py
|
||||
>>> here = time.localtime()
|
||||
>>> here
|
||||
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=12, tm_hour=15, tm_min=44, tm_sec=59, tm_wday=6, tm_yday=285, tm_isdst=0)
|
||||
```
|
||||
Время из кортежа в строку
|
||||
```py
|
||||
>>> time.asctime(here)
|
||||
'Sun Oct 12 15:44:59 2025'
|
||||
```
|
||||
Время из секунд в строку
|
||||
```py
|
||||
>>> time.ctime()
|
||||
'Sun Oct 12 15:46:30 2025'
|
||||
```
|
||||
Пауза
|
||||
```py
|
||||
>>> time.sleep(5)
|
||||
```
|
||||
Из кортежа в секунды с начала эпохи
|
||||
```py
|
||||
>>> time.mktime(here)
|
||||
1760273099.0
|
||||
```
|
||||
## Пункт 7 Графические функции модуля pylab пакета matplotlib
|
||||
```py
|
||||
>>> 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()
|
||||
```
|
||||
Два графика на одном окне
|
||||
```py
|
||||
>>> X1=[12,6,8,10,7]
|
||||
>>> X2=[5,7,9,11,13]
|
||||
>>> pylab.plot(X1) #Создание графика в оперативной памяти
|
||||
[<matplotlib.lines.Line2D object at 0x000001905007A090>]
|
||||
>>> pylab.plot(X2)
|
||||
[<matplotlib.lines.Line2D object at 0x0000019050064D90>]
|
||||
>>> pylab.show()
|
||||
```
|
||||
|
||||
Круговая диаграмма:
|
||||
```py
|
||||
>>> region=['Центр','Урал','Сибирь','Юг']
|
||||
>>> naselen=[65,12,23,17]
|
||||
>>> pylab.pie(naselen,labels=region)
|
||||
([<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()
|
||||
```
|
||||
Гистограмма:
|
||||
```py
|
||||
>>> region=['Центр','Урал','Сибирь','Юг'] #Метки для диаграммы
|
||||
>>> naselen=[65,12,23,17] # Значения для диаграммы
|
||||
>>> pylab.pie(naselen,labels=region) #Создание диаграммы в памяти
|
||||
([<matplotlib.patches.Wedge object at 0x000001904BFBD350>, <matplotlib.patches.Wedge object at 0x000001904F822550>, <matplotlib.patches.Wedge object at 0x000001904F83E5D0>, <matplotlib.patches.Wedge object at 0x000001904F83FC50>], [Text(-0.191013134139045, 1.0832885038559115, 'Центр'), Text(-0.861328292412156, -0.6841882582231001, 'Урал'), Text(0.04429273995539947, -1.0991078896938387, 'Сибирь'), Text(0.9873750693480946, -0.48486129194837324, 'Юг')])
|
||||
>>> pylab.show() #Отображение диаграммы
|
||||
```
|
||||
Столбиковая диаграмма:
|
||||
```py
|
||||
>>> a=['cat','dog','frog']
|
||||
>>> v=[10,55,100]
|
||||
>>> pylab.bar(a,v,color='purple')
|
||||
<BarContainer object of 3 artists>
|
||||
>>> pylab.show()
|
||||
```
|
||||
## Пункт 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']
|
||||
```
|
||||
Математическое ожидание
|
||||
```py
|
||||
>>> data = [0,11,8,5]
|
||||
>>> statistics.mean(data)
|
||||
6
|
||||
```
|
||||
Медиана
|
||||
```py
|
||||
>>> statistics.median(data)
|
||||
6.5
|
||||
```
|
||||
Среднеквадратичное отклонение
|
||||
```py
|
||||
>>> statistics.stdev(data)
|
||||
4.69041575982343
|
||||
```
|
||||
Дисперсия
|
||||
```py
|
||||
>>> statistics.variance(data)
|
||||
22
|
||||
```
|
||||
Квантили
|
||||
```py
|
||||
>>> statistics.quantiles(data)
|
||||
[1.25, 6.5, 10.25]
|
||||
```
|
||||
Загрузка…
Ссылка в новой задаче