Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

22 KiB

Отчет по теме 4

Володин Денис, А-02-23

Пункт 1

Рабочая среда настроена на нахождение в нужной директории:

>>> import os
>>> os.chdir(r"C:\Users\denvo\OneDrive\Рабочий стол\python-labs\TEMA4")

Пункт 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'>

!!! round использует банковское округление. Это значит, что eсли округляемое число равноудалено от соседних чисел, то оно округляется до ближайшей чётной цифры заданного десятичного разряда. Пример:

>>> round(0.5)
0
>>> round(1.5)
2

Пункт 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)
>>> type(range(76,123,9))
<class 'range'>
>>> list(gg)
[76, 85, 94, 103, 112, 121]
>>> tuple(gg)
(76, 85, 94, 103, 112, 121)
>>> g1 = range(23)
>>> list(g1)
[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() - создание итерируемого объекта из кортежей

>>> qq = ["Volodin", "Antonov", "Kireev", "Begenar"]
>>> ff = zip (gg, qq)
>>> ff
<zip object at 0x00000158BF1BB280>
>>> tuple(ff)
((76, 'Volodin'), (85, 'Antonov'), (94, 'Kireev'), (103, 'Begenar'))
  1. Длина получившегося объекта - меньшая из длин объектов-параметров. В данном случае, это 4.
  2. Объект класса zip не итерируемый и не изменяемый
>>> ff[1]
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    ff[1]
TypeError: 'zip' object is not subscriptable

Пункт 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')
коэффициент усиления=73
>>> fff
73.0
>>> dan
209.0

Пункт 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

Пункт 2.6

--Возвращение модуля (abs)--

>>> abs(-98)
98
>>> abs(5 + 4j)
6.4031242374328485

--Возведение в степень--

>>> pow(5,4)
625
>>> pow(5,4,10)
5

--Максимальное из значений--

>>> max(38,15,-6)
38
>>> max([-4,0,5])
5
>>> max({'a': 11, '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(["hehe", "hehehe", "hehehehe"], key = len)
'hehehehe'

>>> max("b", "B")
'b'

Пояснение: тут python сравнивает коды символов в unicode. у "b" это 98, а у "B" - 66.

--Поиск минимума--

Aналогичнo максимуму

>>> min(float("-inf"), -99, 0, 12)
-inf

--Сумма элементов--

>>> sum([1,2,3,4])
10
>>> sum([1,2,3,4], -5)
5
>>> sum("hehe", "haha")
Traceback (most recent call last):
  File "<pyshell#79>", line 1, in <module>
    sum("hehe", "haha")
TypeError: sum() can't sum strings [use ''.join(seq) instead]

--Возвращение кортежа из целой части и остатка от деления--

>>> 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((4,2,1))
3
>>> len("mewmewmewmewm")
13
>>> len(["mewmewmewmewm", "mewmew"])
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(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.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.

>>> 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.

>>> 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)
[]

--Случайное число, подчиняющееся бета-распределению--

>>> 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
1727645502.8504922
>>> c2=time.time()-c1
>>> c2
12.900742053985596

Возвращается время в секундах с начала эпохи 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)

>>> dat=time.gmtime()
>>> list(dat)
[2025, 10, 4, 8, 45, 23, 6, 278, 0]
>>> dat.tm_mon
10
>>> dat.tm_year
2025
>>> dat.tm_yday
278

--Текущее время с учетом часового пояса--

>>> here = time.localtime()
>>> list(here)
[2025, 10, 4, 11, 45, 23, 6, 278, 0]

--Время из кортежа в строку--

>>> time.asctime(here)
'Sut Oct 4 11:48:09 2025'

--Пауза--

>>> time.sleep(5)

--Из кортежа в секунды с начала эпохи--

>>> time.mktime(here)
1728590215.0

Пункт 7

Графические функции модуля pylab пакета matplotlib

>>> import matplotlib
>>> import pylab
>>> x=list(range(-3,55,4))
>>> t=list(range(15))
>>> pylab.plot(t,x) 
>>> pylab.title('Первый график')
>>> pylab.xlabel('время')
>>> pylab.ylabel('сигнал')
>>> pylab.show()

Два графика на одном окне:

>>> X1=[12,6,8,10,7]
>>> X2=[5,7,9,11,13]
>>> pylab.plot(X1)
>>> pylab.plot(X2)
>>> pylab.show()

Гистограмма:

>>> data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]  
>>> pylab.hist(data, bins=5)  
>>> pylab.show() 

Круговая диаграмма:

>>> region=['Центр','Урал','Сибирь','Юг']
>>> naselen=[65,12,23,17]
>>> pylab.hist(naselen,labels=region)
>>> pylab.show()

Столбиковая диаграмма:

>>> 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()

Пункт 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]
>>> s.mean(data)
30

--Медиана--

>>> s.median(data)
30

--Среднеквадратичное отклонение--

>>> s.stdev(data)
15.811388300841896

--Дисперсия--

>>> s.variance(data)
250

--Квантили--

>>> data = [10, 56, 73, 7, 20, 30, 40, 50, 56, 77, 3]
>>> s.quantiles(data)
[10.0, 40.0, 56.0]

По умолчанию n = 4, это квартили. Можно указать 100, например, для процентилей.