13 KiB
Отчёт по теме 4
Зеленкина Катерина Михайловна, А-02-23
Пункт 1. Запуск IDLE
Пункт 2. Стандартные функции
Пункт 2.1. Функция round
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.
>>> a=round(123.456,1); a; type(a)
123.5
<class 'float'>
>>> b=round(123.456,0); b; type(b)
123.0
<class 'float'>
Пояснение: Разница только в количестве знаков после запятой в результате (в первом - до 1 десятичного знака, во-втором - до 0), но тип данных одинаковый
>>> c=round(123.456); c; type(c)
123
<class 'int'>
Пояснение: Произошло округление до целого, и сохранился в "int"
Пункт 2.2. Функция range
range - создание последовательности целых чисел с заданным шагом или, по умолчанию, с шагом 1.
>>> gg=range(76,123,9); gg #генерирует числа с 76 до 123 (пока не будет больше/равно) с шагом 9
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
zip - создание общего объекта, элементами которого являются кортежи, составленные из элементов двух или более объектов-последовательностей
>>> qq=["Зеленкина", "Криви", "Цветкова", "Коломейцев"]
>>> list(gg)
[76, 85, 94, 103, 112, 121]
>>> ff=zip(gg,qq); ff
<zip object at 0x0000020E046D74C0>
>>> type(ff)
<class 'zip'>
>>> tuple(ff)
((76, 'Зеленкина'), (85, 'Криви'), (94, 'Цветкова'), (103, 'Коломейцев'))
>>> ff[0]
Traceback (most recent call last):
File "<pyshell#175>", line 1, in <module>
ff[0]
TypeError: 'zip' object is not subscriptable
>>> ff_list= list(zip(gg, qq)); ff_list[0]
(76, 'Зеленкина')
Пункт 2.4. Функция eval
eval - вычисление значения выражения, корректно записанного на языке Python и представленного в виде символьной строки
>>> fff=float(input('коэффициент усиления=')); dan=eval('5*fff-156')
коэффициент усиления=20
>>> dan
-56.0
Пункт 2.5. Функция exec
exec - чтение и выполнение объекта-аргумента функции.
exec(input('введите инструкции:'))
введите инструкции:perem=-123.456;gg=round(abs(perem)+98,3)
gg
221.456
Пункт 2.6. Самостоятельное применение функций
>>> abs(-100)
100
>>> pow(5,2)
25
>>> max(1,2,3,4,199, 13)
199
>>> min(4,5,-10,-3,2)
-10
>>> sum([4,8,3])
15
>>> divmod(8,2)
(4, 0)
>>> len('Привет, друг!')
13
>>> n=[10,20,30,45]
>>> map(str,n)
<map object at 0x0000020E046CB100>
>>> list(map(str,n))
['10', '20', '30', '45']
Пункт 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!.
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:
>>> math.sin(45)
0.8509035245341184
>>> math.acos(0.8509035245341184)
0.553093477052002
>>> math.degrees(180)
10313.240312354817
>>> math.exp(1)
2.718281828459045
>>> math.log(10)
2.302585092994046
>>> math.log(4,2)
2.0
>>> math.log10(10)
1.0
>>> math.sqrt(16)
4.0
>>> math.ceil(10.8)
11
>>> math.ceil(-10.8)
-10
>>> math.floor(5.5)
5
>>> math.pi
3.141592653589793
Пункт 4. Функции из модуля cmath
Cовокупность функций для работы с комплексными числами.
>>> 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
Cовокупность функций для выполнения операций с псевдослучайными числами и выборками.
>>> 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 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(52)
>>> random.random()
0.9783548583709967
>>> random.uniform(1, 5)
1.2180906200418296
>>> random.randint(1, 10)
9
>>> random.gauss(0, 2)
-4.744196627534718
>>> a=[15,6,8,10]
>>> random.shuffle(a); a
[8, 6, 15, 10]
>>> random.sample(range(10), 2)
[7, 0]
>>> random.sample(range(10), 3)
[0, 8, 6]
>>> random.betavariate(3, 2)
0.7782580563898469
>>> random.gammavariate(3, 2)
7.541042451721967
Создайте список с 4 случайными значениями^
>>> r = [random.uniform(0, 20), random.gauss(13, 33),
random.betavariate(5, 15), random.gammavariate(9, 2)]; r
[9.981907966137051, 20.964805026393023, 0.13659209100569777, 10.30243231589178]
Пункт 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
1759666696.7083006
>>> c2=time.time()-c1; c2
15.599524736404419
>>> dat=time.gmtime(); dat
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=5, tm_hour=12, tm_min=20, tm_sec=10, tm_wday=6, tm_yday=278, tm_isdst=0)
>>>dat.tm_mon
10
>>> dat.tm_year
2025
>>> dat.tm_mday
5
>>> dat.tm_hour
12
>>> dat.tm_min
20
>>> dat.tm_sec
10
>>> dat.tm_wday
6
>>> time.localtime()
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=5, tm_hour=15, tm_min=23, tm_sec=36, tm_wday=6, tm_yday=278, tm_isdst=0)
>>> time.asctime()
'Sun Oct 5 15:23:46 2025'
>>> time.ctime()
'Sun Oct 5 15:23:52 2025'
>>> time.sleep(3)
>>> t=(2025, 10, 5, 15, 23, 36, 6, 278, 0)
>>> obj= time.struct_time(t); obj
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=5, tm_hour=15, tm_min=23, tm_sec=36, tm_wday=6, tm_yday=278, tm_isdst=0)
>>> s=time.mktime(obj);s
1759667016.0
>>> back=time.localtime(s);back
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=5, tm_hour=15, tm_min=23, tm_sec=36, tm_wday=6, tm_yday=278, tm_isdst=0)
Пункт 7. Графические функции
>>> import pylab
>>> x=list(range(-3,55,4))
>>> t=list(range(15))
>>> pylab.plot(t,x)
[<matplotlib.lines.Line2D object at 0x000001FA91846350>]
>>> 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 0x000001FA92FFED50>]
>>> pylab.plot(X2)
[<matplotlib.lines.Line2D object at 0x000001FA92FFEE90>]
>>> pylab.show()
Построение круговой диаграммы
>>> region=['Центр','Урал','Сибирь','Юг']
>>> naselen=[65,12,23,17]
>>> pylab.pie(naselen,labels=region)
([<matplotlib.patches.Wedge object at 0x000001FA918016A0>, <matplotlib.patches.Wedge object at 0x000001FA9257CB90>, <matplotlib.patches.Wedge object at 0x000001FA9257CF50>, <matplotlib.patches.Wedge object at 0x000001FA9257D1D0>], [Text(-0.191013134139045, 1.0832885038559115, 'Центр'), Text(-0.861328292412156, -0.6841882582231001, 'Урал'), Text(0.04429273995539947, -1.0991078896938387, 'Сибирь'), Text(0.9873750693480946, -0.48486129194837324, 'Юг')])
>>> pylab.show()
Гистограммы и столбиковые диаграммы
Построим гистограмму:
>>> import matplotlib.pyplot as plt
>>> ocenki = [3, 4, 4, 5, 5, 5, 4, 3, 5, 4, 5, 5, 4, 3]
>>> plt.hist(ocenki, color='orange', edgecolor='black')
(array([3., 0., 0., 0., 0., 5., 0., 0., 0., 6.]), array([3. , 3.2, 3.4, 3.6, 3.8, 4. , 4.2, 4.4, 4.6, 4.8, 5. ]), <BarContainer object of 10 artists>)
>>> plt.title('Распределение оценок в классе')
Text(0.5, 1.0, 'Распределение оценок в классе')
>>> plt.xlabel('Оценки')
Text(0.5, 0, 'Оценки')
>>> plt.ylabel('Количество учеников')
Text(0, 0.5, 'Количество учеников')
>>> plt.show()
Построим столбиковую диаграмму:
>>> name = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт']
>>> number = [10, 25, 15, 30, 20]
>>> plt.bar(name, number, color='skyblue')
<BarContainer object of 5 artists>
>>> plt.title('Моя диаграмма')
Text(0.5, 1.0, 'Моя диаграмма')
>>> plt.xlabel('Дни недели')
Text(0.5, 0, 'Дни недели')
>>> plt.ylabel('Значения')
Text(0, 0.5, 'Значения')
>>> plt.show()
Пункт 8. Состав модуля statistics
>>> import statistics
>>> g = [45, 50, 55, 60, 65, 70, 75, 80, 85, 200]
>>> mean = statistics.mean(g); mean
78.5
>>> mode = statistics.mode(g); mode
45
>>>stdev = statistics.stdev(g); stdev
44.60007473835292
>>> variance = statistics.variance(g); variance
1989.1666666666667
>>> quantiles = statistics.quantiles(g, n=4); quantiles
[53.75, 67.5, 81.25]
>>> harmonic_mean = statistics.harmonic_mean(g); harmonic_mean
66.96171069719155




