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

11 KiB

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

Махнов Георгий, А-01-23

Тема 4. Встроенные функции

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
>>> round(123.456,0) 
123.0
>>> type(round(123.456,0))
<class 'float'>

Ответы различаются тем, что в первом вызове мы округляем до 1 знака после запятой, во втором вызове мы округляем до 0 знака после запятой (т.е. до целого числа)

>>> round(123.456)
123
>>> type(round(123.456))
<class 'int'>

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]

Получается объект с целыми числами с шагом 1 от 0 до 22.

2.3. Функция zip – создание общего объекта, элементами которого являются кортежи, составленные из элементов двух или более объектов-последовательностей (zip – застежка-«молния»)

>>> qq = ['Махнов','Лазарев','Коваленко','Иванов']
>>> ff=zip(gg,qq)
>>> ff
<zip object at 0x0000018777428980>
>>> tuple(ff)
((76, 'Махнов'), (85, 'Лазарев'), (94, 'Коваленко'), (103, 'Иванов'))
>>> ff[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'zip' object is not subscriptable

В кортеже содержится 4 элемента, так как zip() объединяет 2 объекта по длине меньшего из них (в нашем случае qq, 4 объекта).

2.4. Функция eval – вычисление значения выражения, корректно записанного на языке Python и представленного в виде символьной строки.

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

2.5. Функция 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(-13)
13
>>> pow(-13, 2)
169
>>> max(-13, 12)
12
>>> min(-13, 12) 
-13
>>> sum([-13, 12]) 
-1
>>> divmod(13, 3)
(4, 1)
>>> list(map(int, [14.3, 15.6]))
[14, 15]

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', '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
>>> from math import *
>>> sin(pi/2)
1.0
>>> acos(0.5) 
1.0471975511965979
>>> degrees(13)
744.8451336700703
>>> radians(pi/2)
0.027415567780803774
>>> exp(3)
20.085536923187668
>>> log(4)
1.3862943611198906
>>> log(4,2)
2.0
>>> log10(4)
0.6020599913279624
>>> ceil(3.1) 
4
>>> ceil(-13.3) 
-13
>>> floor(-13.3)
-14
>>> pi
3.141592653589793
>>> sin(2*pi/(7+exp(0.23)))
0.6895048136223223

4. Функции из модуля cmath – совокупность функций для работы с комплексными числами.

>>> import cmath
>>> from cmath import *
>>> 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']
>>> sqrt(1.2-0.5j)
(1.118033988749895-0.22360679774997896j)
>>> cmath.phase(1-0.5j)
-0.4636476090008061

Начните с импорта модуля import cmath Отобразите атрибуты модуля, показывающие содержащиеся в нем функции: dir(cmath) Изучите функцию для извлечения квадратного корня из комплексного числа cmath.sqrt(1.2-0.5j) и функцию расчета фазы cmath.phase(1-0.5j)

5. Стандартный модуль random – совокупность функций для выполнения операций с псевдослу-чайными числами и выборками.

>>> from random import *
>>> dir(random)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
>>> help(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.
>>> seed()
>>> random()
0.9886498397075144
>>> uniform(1, 4)
2.780130303169699
>>> randint(1, 5)
5
>>> gauss(1, 4)
-1.8813369397077917
>>> lst = [1,4,3,5,6]
>>> shuffle(lst) 
>>> print(lst)
[4, 6, 3, 1, 5]
>>> sample(lst, 3)
[3, 1, 5]
>>> betavariate(1, 3)
0.13265164490875223
>>> gammavariate(1,3)
6.693731601234578
>>> [uniform(1,3), gauss(1,3), betavariate(1,3), gammavariate(1,3)]
[2.727738971034954, 0.6065095462022692, 0.454597873888903, 1.6408773406150745]

6. Функции из модуля time – работа с календарем и со временем.

>>> from time import *
>>> dir(time)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
>>> c1 = time()
>>> c1
1760084354.1531947
>>> c2=time()-c1      
>>> c2
7.051163673400879
>>> gmtime()
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=10, tm_hour=8, tm_min=19, tm_sec=40, tm_wday=4, tm_yday=283, tm_isdst=0)
>>> dat = gmtime()
>>> dat.tm_mon
10
>>> dat.tm_hour, dat.tm_min
(8, 20)
>>> localtime()
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=10, tm_hour=11, tm_min=21, tm_sec=3, tm_wday=4, tm_yday=283, tm_isdst=0)
>>> asctime(localtime())
'Fri Oct 10 11:21:55 2025'
>>> ctime(c1)
'Fri Oct 10 11:19:14 2025'
>>> sleep(3)
>>> mktime(localtime())
1760084701.0

7. Графические функции.

>>> import pylab 
>>> x=list(range(-3,55,4))
>>> t=list(range(15))
>>> pylab.plot(t,x)
[<matplotlib.lines.Line2D object at 0x000001E04A97D948>]
>>> pylab.title('Первый график')
Text(0.5, 1.0, 'Первый график')
>>> pylab.xlabel('время')
Text(0.5, 0, 'время')
>>> pylab.ylabel('сигнал')
Text(0, 0.5, 'сигнал')
>>> pylab.show()

alt text

>>> X1=[12,6,8,10,7]                     
>>> X2=[5,7,9,11,13]                    
>>> pylab.plot(X1)
[<matplotlib.lines.Line2D object at 0x000001E04B72CDC8>]
>>> pylab.plot(X2)
[<matplotlib.lines.Line2D object at 0x000001E04B8746C8>]
>>> pylab.show()

alt text

>>> region=['Центр','Урал','Сибирь','Юг']
>>> naselen=[65,12,23,17]
>>> pylab.pie(naselen,labels=region)
([<matplotlib.patches.Wedge object at 0x000001E04C00AA48>, <matplotlib.patches.Wedge object at 0x000001E04C0021C8>, <matplotlib.patches.Wedge object at 0x000001E04A6BCCC8>, <matplotlib.patches.Wedge object at 0x000001E04C139A08>], [Text(-0.1910130855889933, 1.083288512416601, 'Центр'), Text(-0.8613283319035216, -0.6841882085072037, 'Урал'), Text(0.04429273729355889, -1.0991078898011077, 'Сибирь'), Text(0.9873752043868569, -0.4848610169543564, 'Юг')])
>>> pylab.show()

alt text

>>> pylab.hist(X1, bins = 5)
(array([2., 1., 0., 1., 1.]), array([ 6. ,  7.2,  8.4,  9.6, 10.8, 12. ]), <BarContainer object of 5 artists>)
>>> pylab.show()

alt text

>>> values = [13,14,10,18]
>>> categories = ['A', 'B', 'C', 'D']
>>> pylab.bar(categories, values)  
<BarContainer object of 4 artists>
>>> pylab.show()

alt text

8. Самостоятельно изучите состав статистического модуля statistics. Попробуйте применить не менее 3-х функций из этого модуля.

>>> import statistics
>>> statistics
<module 'statistics' from 'C:\\Users\\gmack\\AppData\\Local\\Programs\\Python\\Python37\\lib\\statistics.py'>
>>> dir(statistics)
['Decimal', 'Fraction', 'StatisticsError', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_coerce', '_convert', '_counts', '_exact_ratio', '_fail_neg', '_find_lteq', '_find_rteq', '_isfinite', '_ss', '_sum', 'bisect_left', 'bisect_right', 'collections', 'groupby', 'harmonic_mean', 'math', 'mean', 'median', 'median_grouped', 'median_high', 'median_low', 'mode', 'numbers', 'pstdev', 'pvariance', 'stdev', 'variance']
>>> lst = [1,4,3,5,6,7,83,5,63,5,78,12,5,7,1,4,19]
>>> mean(lst)
18.11764705882353
>>> median(lst)
5
>>> mode(lst)
5