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

23 KiB

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

Шинкаренко Варвара, А-02-23

1. Настроили рабочий каталог

import os
os.chdir('C:\\Users\\LENOVO\\Desktop\\python-labs\\TEMA3')

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

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 = ["Шинкаренко", "Антонов", "Иванов", "Петров"]
ff = zip (gg, qq)
ff
<zip object at 0x00000158BF1BB280>
tuple(ff)
((76, 'Шинкаренко'), (85, 'Антонов'), (94, 'Иванов'), (103, 'Петров'))

#Длина получившегося объекта - меньшая из длин объектов-параметров. В данном случае, это 4.

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 - вычисление выражения строкой

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(-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,4)
625
pow(5,4,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(34,5,6)
34
max([4,0,-5])
4
max({'a': 1, 'b': 2, 'c': 3})
'c'
# Выбор большего происходит из ключей. Видно, что среди буквенных символов больше то, которое ближе к концу алфавита

# С ключом (ключ - это функция, которая поясняет, по какому именно принципу ищем большее):
max(["hehe", "hehehe", "hehehehe"], key = len)
'hehehehe'

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

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

# Поиск минимума
min(float("-inf"), -99, 0, 12)
-inf

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

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

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(5)
1.6094379124341003
math.log(25,5)
2.0

# Десятичный логарифм

math.log10(0.0001)
-4.0
math.log10(10000)
4.0

# Извлечение квадратного корня

math.sqrt(49)
7.0


# Округление числа до ближайшего целого вверх

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

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

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']

c1 = time.time()
c1
1760324194.1891794
c2=time.time()-c1
c2
13.196516513824463

# Возвращается время в секундах с начала эпохи 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, 13, 2, 43, 20, 0, 286, 0]
dat.tm_mon
10
dat.tm_year
2025
dat.tm_yday
286
dat.tm_isdst
0

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

here = time.localtime()
list(here)
[2025, 10, 13, 5, 45, 1, 0, 286, 0]

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

time.asctime(here)
'Mon Oct 13 05:45:01 2025'

# Время из секунд в строку

time.ctime()
'Mon Oct 13 05:46:25 2025'

# Пауза

time.sleep(5)

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

time.mktime(here)
1760323501.0
time.localtime(c1)
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=13, tm_hour=5, tm_min=56, tm_sec=34, tm_wday=0, tm_yday=286, tm_isdst=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 0x000001BC059DA5D0>]

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 0x000001BC05A8D590>]
pylab.plot(X2)
[<matplotlib.lines.Line2D object at 0x000001BC05A8D6D0>]
pylab.show()

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

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

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

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

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

categories = ['Яблоки', 'Бананы', 'Вишня', 'Груши']
values = [10, 15, 7, 12]
plt.bar(categories, values, color='lightgreen', edgecolor='black')
<BarContainer object of 4 artists>
plt.title('Столбиковая диаграмма')
Text(0.5, 1.0, 'Столбиковая диаграмма')
plt.xlabel('Фрукты')
Text(0.5, 0, 'Фрукты')
plt.ylabel('Количество')
Text(0, 0.5, 'Количество')
pylab.show()

Гистограмма

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

categories = ['Яблоки', 'Бананы', 'Вишня', 'Груши']
values = [10, 15, 7, 12]
plt.bar(categories, values, color='lightgreen', edgecolor='black')
<BarContainer object of 4 artists>
plt.title('Столбиковая диаграмма')
Text(0.5, 1.0, 'Столбиковая диаграмма')
plt.xlabel('Фрукты')
Text(0.5, 0, 'Фрукты')
plt.ylabel('Количество')
Text(0, 0.5, 'Количество')
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

# Если объект пустой, вернет StatisticsError

# Медиана

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, например, для процентилей.

9. Завершили сеанс работы