9.1 KiB
Отчёт по теме 4. Операция с объектами
Выполнил Огарков Илья, А-03-23
1. Начало работы
Создание текстового файла report.md
2. Стандартные функции
2.1. Функция round – округление числа с заданной точностью
round(123.456,1) 123.5 round(123.456,0) 123.0
2.2. Функция range – создание последовательности целых чисел с заданным шагом или, по умолчанию, с шагом 1.
gg=range(76,123,9);gg range(76, 123, 9) list(gg) [76, 85, 94, 103, 112, 121] 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]
2.3. ункция zip – создание общего объекта, элементами которого являются кортежи, составленные из элементов двух или более объектов-последовательностей (zip – застежка-«молния»).
qq = ["Ogarkov", "Butko", "Efimova", "Baranov"] ff=zip(gg,qq);ff <zip object at 0x0000021A399B9A00> tuple(ff) ((76, 'Ogarkov'), (85, 'Butko'), (94, 'Efimova'), (103, 'Baranov'))
2.4. Функция eval – вычисление значения выражения, корректно записанного на языке Python и представленного в виде символьной строки
fff=float(input('коэффициент усиления=')); dan=eval('5*fff-156') коэффициент усиления=4 dan -136.0
2.5. Похожая на eval функция exec – чтение и выполнение объекта-аргумента функции
exec(input('введите инструкции:')) введите инструкции:perem=-123.456;gg=round(abs(perem)+98,3) gg 221.456
2.6. Самостоятельно изучите и попробуйте применить функции abs, pow, max, min, sum, divmod, len, map
abs(-7+4) 3 pow(2,3) 8 max(2,3) 3 min(2,3) 2 li_st = [1,2,3,4,5] sum(li_st) 15 divmod(8,3) (2, 2) words = ["apple","orange","limon"] length = map(len, words);length <map object at 0x0000021A3C28AD10> list(length) [5, 6, 5]
3. Функции из стандартного модуля math – совокупность разнообразных математических функций
import math 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 math.sin(30) -0.9880316240928618 math.acos(1) 0.0 math.degrees(120) 6875.493541569878 math.degrees(1) 57.29577951308232 math.radians(180) 3.141592653589793 math.exp(2) 7.38905609893065 math.log(10) 2.302585092994046 math.log(2) 0.6931471805599453 log10(10) math.log10(10) 1.0 math.sqrt(10) 3.1622776601683795 math.ceil(10.2) 11 math.floor(10.2) 10 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 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.
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'] random.seed(5) random.random() 0.7417869892607294 random.gauss(170,5) 171.01449055876262 random.gauss(170,5) 175.5048579816218 numbers = [1,3,5,3,8,9] random.choice(numbers) 3 random.shuffle(numbers);numbers [8, 3, 9, 3, 5, 1] random.sample(numbers, 3) [5, 8, 3] random.betavariate(1,100) 0.00014457630861401468 random.gammavariate(1,100) 248.10585250290603
6. Функции из модуля time – работа с календарем и со временем
<module 'time' (built-in)> c1=time.time();c1 1759135155.9747162 c2=time.time()-c1 c2 21.171961307525635 dat=time.gmtime();dat time.struct_time(tm_year=2025, tm_mon=9, tm_mday=29, tm_hour=8, tm_min=40, tm_sec=13, tm_wday=0, tm_yday=272, tm_isdst=0) dat.tm_mon 9 dat.tm_mday 29 time.localtime tm=time.localtime();tm time.struct_time(tm_year=2025, tm_mon=9, tm_mday=29, tm_hour=11, tm_min=42, tm_sec=48, tm_wday=0, tm_yday=272, tm_isdst=0) time.ctime() 'Mon Sep 29 11:44:13 2025' time.asctime() 'Mon Sep 29 11:44:25 2025' time.localtime(c1) time.struct_time(tm_year=2025, tm_mon=9, tm_mday=29, tm_hour=11, tm_min=39, tm_sec=15, tm_wday=0, tm_yday=272, tm_isdst=0)
7. Графические функции
import pylab Matplotlib is building the font cache; this may take a moment. x=list(range(-3,55,4)) t=list(range(15)) pylab.plot(t,x) [<matplotlib.lines.Line2D object at 0x0000021A451EB250>] 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 0x0000021A46656C50>] pylab.plot(X2) [<matplotlib.lines.Line2D object at 0x0000021A46657390>] pylab.show() region=['Центр','Урал','Сибирь','Юг'] naselen=[65,12,23,17] pylab.pie(naselen,labels=region) ([<matplotlib.patches.Wedge object at 0x0000021A46675650>, <matplotlib.patches.Wedge object at 0x0000021A4A8989D0>, <matplotlib.patches.Wedge object at 0x0000021A4A899ED0>, <matplotlib.patches.Wedge object at 0x0000021A4A89B4D0>], [Text(-0.191013134139045, 1.0832885038559115, 'Центр'), Text(-0.861328292412156, -0.6841882582231001, 'Урал'), Text(0.04429273995539947, -1.0991078896938387, 'Сибирь'), Text(0.9873750693480946, -0.48486129194837324, 'Юг')]) pylab.show() pylab.plot(t,x) [<matplotlib.lines.Line2D object at 0x0000021A4A8D6C90>] pylab.title('Первый график') Text(0.5, 1.0, 'Первый график') pylab.xlabel('время') Text(0.5, 0, 'время') pylab.ylabel('сигнал') Text(0, 0.5, 'сигнал') pylab.show() pylab.plot(X1) [<matplotlib.lines.Line2D object at 0x0000021A4A8A8CD0>] pylab.plot(X2) [<matplotlib.lines.Line2D object at 0x0000021A4A9173D0>] pylab.show() region=['Центр','Урал','Сибирь','Юг'] naselen=[65,12,23,17] pylab.pie(naselen,labels=region) ([<matplotlib.patches.Wedge object at 0x0000021A467F10D0>, <matplotlib.patches.Wedge object at 0x0000021A467C6550>, <matplotlib.patches.Wedge object at 0x0000021A467F3410>, <matplotlib.patches.Wedge object at 0x0000021A46800A50>], [Text(-0.191013134139045, 1.0832885038559115, 'Центр'), Text(-0.861328292412156, -0.6841882582231001, 'Урал'), Text(0.04429273995539947, -1.0991078896938387, 'Сибирь'), Text(0.9873750693480946, -0.48486129194837324, 'Юг')]) pylab.show() naselen=[65,12,23,17] pylab.hist(naselen) (array([2., 0., 1., 0., 0., 0., 0., 0., 0., 1.]), array([12. , 17.3, 22.6, 27.9, 33.2, 38.5, 43.8, 49.1, 54.4, 59.7, 65. ]), <BarContainer object of 10 artists>) pylab.show() pylab.bar(naselen, 3) <BarContainer object of 4 artists> pylab.show()
8. Статистический модуль statistics
import statistics numbers = [1,2,3,4,5,6,7,8,9] statistics.mean(numbers) 5 statistics.median(numbers) 5 statistics.mod(numbers) statistics.mode(numbers) 1