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

9.8 KiB

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

Мамакин Ярослав, А-02-23

1 Начало работы

Запустил среду IDLE, установил рабочую папку.

2 Стандартные функции из модуля builtins.

2.1 Функция округления

>>>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
>>>round(123.456,0)
123.0
>>>round(123.456)
123

В первых двух случаях тип float, во втором - int.

2.2 Функция создания последовательности

>>>gg=range(76, 123, 9)
>>>type(gg)
<class 'range'>
>>>list(gg)
[76, 85, 94, 103, 112, 121]
>>>range(23) # последовательность целых чисел от 0 до 22 включительно с шагом 1
range(0, 23)

2.3 Функция zip

>>>qq = ['Мамакин','Савин','Симанков','Киреев']
>>>ff=zip(gg,qq)
>>>tuple(ff)
((76, 'Мамакин'), (85, 'Савин'), (94, 'Симанков'), (103, 'Киреев'))
>>>ff[1]
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    ff[1]
TypeError: 'zip' object is not subscriptable

К объекту zip с указанием индекса обращаться нельзя.

2.4 Функция eval

>>>fff=float(input('коэффициент усиления='))
коэффициент усиления=54
>>>dan=eval('5*fff-156')
>>>dan
114.0

2.5 Функция exec

>>>exec(input('введите инструкции:'))
введите инструкции:perem=-123.456;gg=round(abs(perem)+98,3)
>>>gg
221.456

2.6 Другие встроенные функции

list(map(len, qq))
[7, 5, 8, 6] # Длины фамилий из списка qq
divmod(64,5)
(12, 4) # Кортеж с частным и остатком при делении 64 на 5

3 Модуль math

>>>import math
>>>dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fma', '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', 'sumprod', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
>>>help(math.factorial)
Help on built-in function factorial in module math:

factorial(n, /)
    Find n!.

>>>math.factorial(5)
120
>>>math.degrees(math.acos(math.sin(math.pi)))
90.0
>>>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', '_ONE', '_Sequence', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_fabs', '_floor', '_index', '_inst', '_isfinite', '_lgamma', '_log', '_log2', '_os', '_parse_args', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', 'betavariate', 'binomialvariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'main', 'normalvariate', 'paretovariate', 'randbytes', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
>>>help(random.seed())
Help on NoneType object:

class NoneType(object)
 |  The type of the None singleton.
 |
 |  Methods defined here:
 |
 |  __bool__(self, /)
 |      True if self else False
 |
 |  __eq__(self, value, /)
 |      Return self==value.
 |
 |  __ge__(self, value, /)
 |      Return self>=value.
 |
 |  __gt__(self, value, /)
 |      Return self>value.
 |
 |  __hash__(self, /)
 |      Return hash(self).
 |
 |  __le__(self, value, /)
 |      Return self<=value.
 |
 |  __lt__(self, value, /)
 |      Return self<value.
 |
 |  __ne__(self, value, /)
 |      Return self!=value.
 |
 |  __repr__(self, /)
 |      Return repr(self).
 |
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |
 |  __new__(*args, **kwargs)
 |      Create and return a new object.  See help(type) for accurate signature.

>>>random.seed()
>>>random.random()
0.6216104315561441
>>>random.uniform(0,1)
0.15558476742451
>>>random.randint(0,100)
65
>>>random.gauss()
-1.2490453714301064
>>>random.choice([1,2,3,4,5])
5
>>>sp = [1,2,3,4,5,6,7,8,9]
>>>random.shuffle(sp)
>>>sp
[8, 2, 5, 9, 6, 7, 1, 3, 4]
>>>random.sample(sp, 3)
[6, 1, 7]
>>>random.betavariate(0.5, 0.5)
0.21196520335129634
>>>random.gammavariate(0.5, 0.5)
0.18678325471924362
>>>sp1 = [random.random(), random.gauss(), random.betavariate(0.5,0.5), random.gammavariate(0.5, 0.5)]
>>>sp1
[0.09352103273802048, 0.41529631729753796, 0.5372987697985309, 0.08540638796369146]

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()
>>>c2=time.time()-c1
>>>c2
13.89244294166565
>>>dat = time.gmtime()
>>>dat.tm_mon
9
>>>dat1 = time.localtime()
>>>dat1.tm_mday
28
>>>time.asctime(dat)
'Sat Sep 27 21:23:38 2025'
>>>time.ctime(564783)
'Wed Jan  7 15:53:03 1970'
>>>time.mktime(dat1)
1759008378.0
>>>time.localtime(c1)
time.struct_time(tm_year=2025, tm_mon=9, tm_mday=28, tm_hour=0, tm_min=22, tm_sec=49, tm_wday=6, tm_yday=271, tm_isdst=0)

7 Модуль pylab

import pylab
x=list(range(-3,55,4))
t=list(range(15))
pylab.plot(t,x)
[<matplotlib.lines.Line2D object at 0x0000020CE16E6850>]
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 0x0000020CE37DB110>]
pylab.plot(X2)
[<matplotlib.lines.Line2D object at 0x0000020CE37DB250>]
pylab.show()

Совмещенные графики

region=['Центр','Урал','Сибирь','Юг']
naselen=[65,12,23,17]
pylab.pie(naselen,labels=region)
([<matplotlib.patches.Wedge object at 0x0000020CE16C9940>, <matplotlib.patches.Wedge object at 0x0000020CE1EBCB90>, <matplotlib.patches.Wedge object at 0x0000020CE1EBCF50>, <matplotlib.patches.Wedge object at 0x0000020CE1EBD1D0>], [Text(-0.191013134139045, 1.0832885038559115, 'Центр'), Text(-0.861328292412156, -0.6841882582231001, 'Урал'), Text(0.04429273995539947, -1.0991078896938387, 'Сибирь'), Text(0.9873750693480946, -0.48486129194837324, 'Юг')])
pylab.show()

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

pylab.hist(X1, 4)
(array([2., 1., 1., 1.]), array([ 6. ,  7.5,  9. , 10.5, 12. ]), <BarContainer object of 4 artists>)
pylab.show()

Гисторамма

pylab.bar(X1, X2)
<BarContainer object of 5 artists>
pylab.show()

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

8 Модуль statistics

import statistics as st
dir(st)
['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', '_kernel_invcdfs', '_mean_stdev', '_newton_raphson', '_normal_dist_inv_cdf', '_quartic_invcdf', '_quartic_invcdf_estimate', '_random', '_rank', '_sqrt_bit_width', '_sqrtprod', '_ss', '_sum', '_triweight_invcdf', '_triweight_invcdf_estimate', 'acos', 'asin', 'atan', 'bisect_left', 'bisect_right', 'correlation', 'cos', 'cosh', 'count', 'covariance', 'defaultdict', 'erf', 'exp', 'fabs', 'fmean', 'fsum', 'geometric_mean', 'groupby', 'harmonic_mean', 'hypot', 'isfinite', 'isinf', 'itemgetter', 'kde', 'kde_random', 'linear_regression', 'log', 'math', 'mean', 'median', 'median_grouped', 'median_high', 'median_low', 'mode', 'multimode', 'namedtuple', 'numbers', 'pi', 'pstdev', 'pvariance', 'quantiles', 'random', 'reduce', 'repeat', 'sin', 'sqrt', 'stdev', 'sumprod', 'sys', 'tan', 'tau', 'variance']
st.mean(X1) # вычисление среднего
8.6
st.median(X2) # вычисление медианы
9
st.linear_regression(X1, X2) # построение простой линейной регрессионной модели
LinearRegression(slope=-0.5172413793103449, intercept=13.448275862068964)