форкнуто от main/python-labs
Родитель
4fcc536ea5
Сommit
d2ec5c8b7a
|
После Ширина: | Высота: | Размер: 20 KiB |
|
После Ширина: | Высота: | Размер: 26 KiB |
|
После Ширина: | Высота: | Размер: 15 KiB |
|
После Ширина: | Высота: | Размер: 12 KiB |
|
После Ширина: | Высота: | Размер: 8.7 KiB |
@ -0,0 +1,768 @@
|
|||||||
|
# Отчет по теме 4
|
||||||
|
|
||||||
|
## 1. Запуск интерактивной оболочки IDLE
|
||||||
|
|
||||||
|
## 2. Стандартные функции
|
||||||
|
|
||||||
|
### 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 не указан, функция возвращает округленное целое число.
|
||||||
|
Если указан, пускай даже ноль, то число будет с плавающей точкой.
|
||||||
|
|
||||||
|
- round использует банковское округление. Это значит, что eсли округляемое число
|
||||||
|
равноудалено от соседних чисел, то оно округляется до ближайшей чётной цифры
|
||||||
|
заданного десятичного разряда.
|
||||||
|
|
||||||
|
### 2.2. Функция range – создание последовательности целых чисел с заданным шагом или, по умолчанию, с шагом 1.
|
||||||
|
|
||||||
|
```
|
||||||
|
>>>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).
|
||||||
|
|
|
||||||
|
| Methods defined here:
|
||||||
|
|
|
||||||
|
| __bool__(self, /)
|
||||||
|
| True if self else False
|
||||||
|
|
|
||||||
|
| __contains__(self, key, /)
|
||||||
|
| Return key in self.
|
||||||
|
|
|
||||||
|
| __eq__(self, value, /)
|
||||||
|
| Return self==value.
|
||||||
|
|
|
||||||
|
| __ge__(self, value, /)
|
||||||
|
| Return self>=value.
|
||||||
|
|
|
||||||
|
| __getattribute__(self, name, /)
|
||||||
|
| Return getattr(self, name).
|
||||||
|
|
|
||||||
|
| __getitem__(self, key, /)
|
||||||
|
| Return self[key].
|
||||||
|
|
|
||||||
|
| __gt__(self, value, /)
|
||||||
|
| Return self>value.
|
||||||
|
|
|
||||||
|
| __hash__(self, /)
|
||||||
|
| Return hash(self).
|
||||||
|
|
|
||||||
|
| __iter__(self, /)
|
||||||
|
| Implement iter(self).
|
||||||
|
|
|
||||||
|
| __le__(self, value, /)
|
||||||
|
| Return self<=value.
|
||||||
|
|
|
||||||
|
| __len__(self, /)
|
||||||
|
| Return len(self).
|
||||||
|
|
|
||||||
|
| __lt__(self, value, /)
|
||||||
|
| Return self<value.
|
||||||
|
|
|
||||||
|
| __ne__(self, value, /)
|
||||||
|
| Return self!=value.
|
||||||
|
|
|
||||||
|
| __reduce__(...)
|
||||||
|
| Helper for pickle.
|
||||||
|
|
|
||||||
|
| __repr__(self, /)
|
||||||
|
| Return repr(self).
|
||||||
|
|
|
||||||
|
| __reversed__(...)
|
||||||
|
| Return a reverse iterator.
|
||||||
|
|
|
||||||
|
| count(...)
|
||||||
|
| rangeobject.count(value) -> integer -- return number of occurrences of value
|
||||||
|
|
|
||||||
|
| index(...)
|
||||||
|
| rangeobject.index(value) -> integer -- return index of value.
|
||||||
|
| Raise ValueError if the value is not present.
|
||||||
|
|
|
||||||
|
| ----------------------------------------------------------------------
|
||||||
|
| Static methods defined here:
|
||||||
|
|
|
||||||
|
| __new__(*args, **kwargs) from builtins.type
|
||||||
|
| Create and return a new object. See help(type) for accurate signature.
|
||||||
|
|
|
||||||
|
| ----------------------------------------------------------------------
|
||||||
|
| Data descriptors defined here:
|
||||||
|
|
|
||||||
|
| start
|
||||||
|
|
|
||||||
|
| step
|
||||||
|
|
|
||||||
|
| stop
|
||||||
|
|
||||||
|
>>>gg = range(76, 123, 9)
|
||||||
|
>>>list(gg)
|
||||||
|
[76, 85, 94, 103, 112, 121]
|
||||||
|
>>>range(23)
|
||||||
|
range(0, 23)
|
||||||
|
>>>type(range(23))
|
||||||
|
<class 'range'>
|
||||||
|
>>>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]
|
||||||
|
```
|
||||||
|
Объект range(23) будет содержать последовательность целых чисел, начиная с 0 и до 22 (так как 23 не включается). Чтобы это увидить, необходимо применить list(). range — это легковесный объект, который генерирует числа на лету, а не хранит их все в памяти, поэтому преобразование в list нужно только для просмотра. Границы диапазона: от 0 и до 23, проход с шагом 1 по умолчанию(Если вызываем просто range(23), выводится только начальное и конечное значение).
|
||||||
|
|
||||||
|
### 2.3. Функция zip - создание итерируемого объекта из кортежей
|
||||||
|
```
|
||||||
|
>>>qq = ["Melnikov", "Baranov", "Podolskiy", "Bushmanov"]
|
||||||
|
>>>ff = zip(gg, qq)
|
||||||
|
>>>ff
|
||||||
|
<zip object at 0x0000021278293500>
|
||||||
|
>>>tuple(ff)
|
||||||
|
((76, 'Melnikov'), (85, 'Baranov'), (94, 'Podolskiy'), (103, 'Bushmanov'))
|
||||||
|
```
|
||||||
|
|
||||||
|
Длина получившегося объекта соответствует длине меньшего объекта-параметров(длина 4 значения).
|
||||||
|
```
|
||||||
|
>>>ff[1]
|
||||||
|
Traceback (most recent call last):
|
||||||
|
File "<pyshell#20>", line 1, in <module>
|
||||||
|
ff[1]
|
||||||
|
TypeError: 'zip' object is not subscriptable
|
||||||
|
```
|
||||||
|
К объекту ff нельзя обратиться по индексу из-за того что он не итерируемый, так же он является не изменяемым.
|
||||||
|
|
||||||
|
### 2.4. Функция eval – вычисление значения выражения, корректно записанного на языке Python и представленного в виде символьной строки.
|
||||||
|
|
||||||
|
```
|
||||||
|
>>>fff=float(input('коэффициент усиления=')); dan=eval('5*fff-156')
|
||||||
|
коэффициент усиления=73
|
||||||
|
>>>fff
|
||||||
|
73.0
|
||||||
|
>>>dan
|
||||||
|
209.0
|
||||||
|
```
|
||||||
|
### 2.5. Функция exec – чтение и выполнение объекта-аргумента функции.
|
||||||
|
```
|
||||||
|
>>>exec(input('введите инструкции:'))
|
||||||
|
введите инструкции:perem=-123.456;gg=round(abs(perem)+98,3)
|
||||||
|
>>>gg
|
||||||
|
221.456
|
||||||
|
```
|
||||||
|
|
||||||
|
- Примечание. Функции eval() и exec() нужно использовать с осторожностью, так как они затрудняют чтение и понимание программОтличие eval() от exec() в том, что eval() вычисляет выражение (expression), а exec() выполняет инструкции (statements). Выражения — подмножество инструкций, отличающееся наличием результата. Например, 1, 1+2, a+3 — выражения, а присваивание или условный оператор — инструкции.
|
||||||
|
|
||||||
|
### 2.6. Функции abs, pow, max, min, sum, divmod, len, map.
|
||||||
|
|
||||||
|
- Функция abs(возвращение модуля):
|
||||||
|
```
|
||||||
|
>>>x = abs(-10)
|
||||||
|
>>>x
|
||||||
|
10
|
||||||
|
```
|
||||||
|
|
||||||
|
- Функция pow(возведение в степень)
|
||||||
|
|
||||||
|
```
|
||||||
|
>>>pow(2, 10)
|
||||||
|
1024
|
||||||
|
>>>pow(4,5,10) # 4**5 = 1024, затем 1024 % 10 = 4
|
||||||
|
4
|
||||||
|
```
|
||||||
|
|
||||||
|
- Функции max и min(выбор максимального и минимального значения соответственно)
|
||||||
|
```
|
||||||
|
>>>max(40, 50, 6)
|
||||||
|
50
|
||||||
|
>>>min(-3, 57, 30)
|
||||||
|
-3
|
||||||
|
```
|
||||||
|
|
||||||
|
- Функция sum(суммирование элементов)
|
||||||
|
```
|
||||||
|
>>>sum([1,2,3,4,5])
|
||||||
|
15
|
||||||
|
>>>sum([1,2,3,4,5], -5)
|
||||||
|
10
|
||||||
|
```
|
||||||
|
|
||||||
|
- Функция divmod(возвращение кортежа из целой части и остатка от деления)
|
||||||
|
```
|
||||||
|
>>>divmod(36, 5)
|
||||||
|
(7, 1)
|
||||||
|
```
|
||||||
|
|
||||||
|
- Функция len(длина списка)
|
||||||
|
```
|
||||||
|
>>>len([1,2,3,4,5,6])
|
||||||
|
6
|
||||||
|
```
|
||||||
|
|
||||||
|
- Функция map ( это встроенная функция 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 – совокупность разнообразных математических функций.
|
||||||
|
```
|
||||||
|
>>>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
|
||||||
|
|
||||||
|
```
|
||||||
|
>>>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
|
||||||
|
```
|
||||||
|
>>>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
|
||||||
|
|
||||||
|
```
|
||||||
|
>>>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
|
||||||
|
```
|
||||||
|
>>>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
|
||||||
|
```
|
||||||
|
>>>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
|
||||||
|
```
|
||||||
|
>>>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
|
||||||
|
```
|
||||||
|
>>>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
|
||||||
|
```
|
||||||
|
>>>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(округление в большую сторону)
|
||||||
|
```
|
||||||
|
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(округление в меньшую сторону)
|
||||||
|
```
|
||||||
|
>>>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
|
||||||
|
```
|
||||||
|
>>>math.pi
|
||||||
|
3.141592653589793
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## 4. Функции из модуля cmath – совокупность функций для работы с комплексными числами.
|
||||||
|
|
||||||
|
```
|
||||||
|
>>>import cmath
|
||||||
|
>>>dir(cmath)
|
||||||
|
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'inf', 'infj', 'isclose', 'isfinite', 'isinf', 'isnan', 'log', 'log10', 'nan', 'nanj', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau']
|
||||||
|
>>>cmath.sqrt(1.2-0.5j) # извлечения квадратного корня из комплексного числа
|
||||||
|
(1.118033988749895-0.22360679774997896j)
|
||||||
|
>>>cmath.phase(1-0.5j) # функция расчета фазы
|
||||||
|
-0.4636476090008061
|
||||||
|
```
|
||||||
|
## 5. Стандартный модуль random – совокупность функций для выполнения операций с псевдослучайными числами и выборками.
|
||||||
|
|
||||||
|
```
|
||||||
|
>>>import random
|
||||||
|
>>>dir(random)
|
||||||
|
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_ONE', '_Sequence', '_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() инициализирует начальное состояние генератора псевдослучайных чисел.
|
||||||
|
|
||||||
|
- Функци random(равномерно распределенное случайное число от 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.15224090837130377
|
||||||
|
>>>random.random()
|
||||||
|
0.8451183120672832
|
||||||
|
>>>random.random()
|
||||||
|
0.8392090272295469
|
||||||
|
```
|
||||||
|
|
||||||
|
- Функция uniform (равномерно распределенное случайное число)
|
||||||
|
```
|
||||||
|
>>>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
|
||||||
|
```
|
||||||
|
|
||||||
|
- Функция gauss(нормально распределенное случайное число)
|
||||||
|
```
|
||||||
|
>>>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(случайные целые числа)
|
||||||
|
```
|
||||||
|
>>>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
|
||||||
|
```
|
||||||
|
|
||||||
|
- Функция choice (случайный выбор из совокупности)
|
||||||
|
```
|
||||||
|
>>>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 (случайная перестановка элементов списка)
|
||||||
|
```
|
||||||
|
>>>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 (случайный выбор подмножества элементов)
|
||||||
|
```
|
||||||
|
>>>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(случайное число с бета-распределением)
|
||||||
|
```
|
||||||
|
>>>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(случайное число с гамма-распределением)
|
||||||
|
```
|
||||||
|
>>>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 случайными значениями, подчиняющимися, соответственно, равномерному, нормальному, бета и гамма – распределениям и с любыми допустимыми значениями параметров этих распределений.
|
||||||
|
|
||||||
|
```
|
||||||
|
>>>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
|
||||||
|
[3.940448252721481, -0.9946853417283795, 0.04299068887668711, 8.97265061419367]
|
||||||
|
```
|
||||||
|
|
||||||
|
## 6. Функции из модуля time – работа с календарем и со временем.
|
||||||
|
|
||||||
|
- UNIX время и текущее время
|
||||||
|
```
|
||||||
|
>>>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=6, tm_hour=8, tm_min=57, tm_sec=30, tm_wday=0, tm_yday=279, tm_isdst=0)
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
- Текущее время с учетом часового пояса
|
||||||
|
```
|
||||||
|
>>>mestn = time.localtime()
|
||||||
|
>>>list(mestn)
|
||||||
|
[2025, 10, 6, 12, 18, 35, 0, 279, 0]
|
||||||
|
```
|
||||||
|
|
||||||
|
- Функция asctime (преобразование представления времени из кортежа в строку)
|
||||||
|
```
|
||||||
|
>>>time.asctime(mestn)
|
||||||
|
|
||||||
|
'Mon Oct 6 12:18:35 2025'
|
||||||
|
```
|
||||||
|
- Функция ctime (преобразование времени в секундах, прошедшего с начала эпохи, в строку)
|
||||||
|
```
|
||||||
|
>>>time.ctime()
|
||||||
|
|
||||||
|
'Mon Oct 6 12:22:01 2025'
|
||||||
|
```
|
||||||
|
|
||||||
|
- Функция sleep (прерывание работы программы на заданное время)
|
||||||
|
```
|
||||||
|
>>>time.sleep(5)
|
||||||
|
```
|
||||||
|
|
||||||
|
- Функция mktime (преобразование времени из типа кортежа или struct_time в число секунд с начала эпохи)
|
||||||
|
```
|
||||||
|
>>>time.mktime(mestn)
|
||||||
|
|
||||||
|
1759742315.0
|
||||||
|
```
|
||||||
|
|
||||||
|
- Обратное преобразование из секунд в местное время
|
||||||
|
```
|
||||||
|
>>>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):
|
||||||
|
|
||||||
|
```
|
||||||
|
>>>import matplotlib
|
||||||
|
>>>import pylab
|
||||||
|
|
||||||
|
>>>x=list(range(-3,55,4))
|
||||||
|
>>>t=list(range(15))
|
||||||
|
>>>pylab.plot(t,x) #Создание графика в оперативной памяти
|
||||||
|
[<matplotlib.lines.Line2D object at 0x0000021222D40400>]
|
||||||
|
>>>pylab.title('Первый график')
|
||||||
|
Text(0.5, 1.0, 'Первый график')
|
||||||
|
>>>pylab.xlabel('время')
|
||||||
|
Text(0.5, 0, 'время')
|
||||||
|
>>>pylab.ylabel('сигнал')
|
||||||
|
Text(0, 0.5, 'сигнал')
|
||||||
|
>>>pylab.show() #Отображение графика на экране
|
||||||
|
```
|
||||||
|
|
||||||
|
- Рассмотрим способ построения нескольких графиков на одном рисунке.
|
||||||
|
```
|
||||||
|
>>>X1 = [12, 6, 8, 10, 7]
|
||||||
|
>>>X2 = [5, 7, 9, 11, 13]
|
||||||
|
>>>pylab.plot(X1)
|
||||||
|
[<matplotlib.lines.Line2D object at 0x0000021222DF35B0>]
|
||||||
|
>>>pylab.plot(X2)
|
||||||
|
[<matplotlib.lines.Line2D object at 0x0000021222DF38B0>]
|
||||||
|
>>>pylab.show()
|
||||||
|
```
|
||||||
|
|
||||||
|
- Теперь изучим возможность построения круговой диаграммы.
|
||||||
|
```
|
||||||
|
>>>region=['Центр','Урал','Сибирь','Юг'] #Метки для диаграммы
|
||||||
|
>>>naselen=[65,12,23,17] # Значения для диаграммы
|
||||||
|
>>>pylab.pie(naselen, labels=region) #Создание диаграммы в памяти
|
||||||
|
([<matplotlib.patches.Wedge object at 0x0000021225094EB0>, <matplotlib.patches.Wedge object at 0x0000021225094DF0>, <matplotlib.patches.Wedge object at 0x0000021225095900>, <matplotlib.patches.Wedge object at 0x0000021225095E70>], [Text(-0.191013134139045, 1.0832885038559115, 'Центр'), Text(-0.861328292412156, -0.6841882582231001, 'Урал'), Text(0.04429273995539947, -1.0991078896938387, 'Сибирь'), Text(0.9873750693480946, -0.48486129194837324, 'Юг')])
|
||||||
|
>>>pylab.show() #Отображение диаграммы
|
||||||
|
```
|
||||||
|
|
||||||
|
- Построение гистограммы
|
||||||
|
```
|
||||||
|
>>>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. ]), <BarContainer object of 10 artists>)
|
||||||
|
>>>pylab.title('Простая гистограмма')
|
||||||
|
Text(0.5, 1.0, 'Простая гистограмма')
|
||||||
|
>>>pylab.xlabel('Значения')
|
||||||
|
Text(0.5, 0, 'Значения')
|
||||||
|
>>>pylab.ylabel('Частота')
|
||||||
|
Text(0, 0.5, 'Частота')
|
||||||
|
>>>pylab.show()
|
||||||
|
```
|
||||||
|
|
||||||
|
- Построение столбиковой диаграммы
|
||||||
|
```
|
||||||
|
>>>fruits = ["apple", "date", "apricot", "raspberry", "watermelon"]
|
||||||
|
>>>values = [13, 16, 8, 25, 6]
|
||||||
|
>>>pylab.bar(fruits, values, color='green')
|
||||||
|
<BarContainer object of 5 artists>
|
||||||
|
>>>pylab.show()
|
||||||
|
```
|
||||||
|
|
||||||
|
Все графики, диаграммы и гистограммы сохранены в папку в формате "jpg".
|
||||||
|
|
||||||
|
## 8. Статистический модуль statics
|
||||||
|
|
||||||
|
```
|
||||||
|
>>>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. Завершение работы
|
||||||
Загрузка…
Ссылка в новой задаче