форкнуто от main/python-labs
Вы не можете выбрать более 25 тем
Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
10 KiB
10 KiB
Отчёт по теме 4
Выполнил Степанищев Виктор, А-03-23
1. Начало работы
Создание текстового файла report.md
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
>>> (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
>>> gg = range(76, 123, 9)
>>> gg
range(76, 123, 9)
>>> list(gg)
[76, 85, 94, 103, 112, 121]
>>> range(23)
range(0, 23)
>>> 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]
Объект с какими значениями получится в этом случае? Каковы границы диапазона? Какой шаг?
Значения: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
Границы: [0, 23)
Шаг: 1
2.3. Функция zip
>>> = ['Stepanishchev', 'Krishtul', 'Ogarkov', 'Markov']
>>> zip(gg, qq)
>>> ff = zip(gg, qq)
>>> tuple(ff)
((76, 'Stepanishchev'), (85, 'Krishtul'), (94, 'Ogarkov'), (103, 'Markov'))
>>> fff = tuple(ff)
>>> len(fff)
4
>>> len(gg), len(qq)
(6, 4)
>>> ff[0]
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'zip' object is not subscriptable
Нельзя обращаться с указанием индекса, т.к. объект является итерируемым класса zip
2.4. Функция eval
>>> fff=float(input('коэффициент усиления=')); dan=eval('5*fff-156')
>>> коэффициент усиления=>? 5
>>> dan
-131.0
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(-14)
14
>>> pow(2, 3)
8
>>> max(1, 2, 3)
3
>>> min(1, 2, 3)
1
>>> sum([1, 2, 3])
6
>>> divmod(5, 3)
(1, 2)
>>> len(range(0, 15+1))
16
>>> map_test = map(lambda x: round(x, 1), [12.1245, 14.125234, 534.222])
>>> list(map_test)
[12.1, 14.1, 534.2]
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
3.1 sin
>>> math.sin(90)
0.8939966636005579
3.2 acos
>>> math.acos(0)
1.5707963267948966
3.3 degrees
>>> math.degrees(math.pi)
180.0
3.4 radians
>>> math.radians(180)
3.141592653589793
3.5 exp
>>> math.exp(1)
2.718281828459045
3.6 log
>>> math.log(10)
2.302585092994046
3.7 log10
>>> math.log10(100)
2.0
3.8 sqrt
>>> math.sqrt(16)
4.0
3.9 ceil
>>> math.ceil(3.14) # округление вверх
4
3.10 floor
>>> math.floor(3.14) # округление вниз
3
3.11 pi
>>> math.pi
3.141592653589793
Вычислите значение функции sin(2π/7+e0.23 )
>>> sin((2*pi/7) + exp(0.23))
0.8334902641414562
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
>>> 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', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'binomialvariate', '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.random() # вещественное число от 0.0 до 1.0
0.12874671061082976
>>> random.uniform(5, 15) # вещественное число от 5.0 до 15.0
13.134575401523493
>>> random.randint(1, 100) # целое число от 1 до 100
32
>>> random.gauss(0, 1) # mu - среднее значение, sigma - стандартное отклонение
-0.07800637063087972
>>> random.choice([1, 2, 3, 4]) # случайный выбор элемента из списка, кортежа, строки и т.д.
3
>>> My_Numbers = [1, 2, 3, 4]
>>> random.shuffle(My_Numbers)
>>> My_Numbers
[1, 2, 4, 3]
>>> random.sample(My_Numbers, 2) # случайный выбор двух элементов из My_Numbers
[4, 1]
>>> random.betavariate(2, 5)
0.16541871582286427
>>> random.gammavariate(2, 1)
0.6551814424330216
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
1759765317.220153
>>> c2=time.time()-c1
>>> c2
12.758715867996216
>>> dat=time.gmtime()
>>> dat
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=6, tm_hour=15, tm_min=43, tm_sec=11, tm_wday=0, tm_yday=279, tm_isdst=0)
>>> dat.tm_mon
10
>>> time.asctime((2024, 12, 10, 18, 7, 14, 1, 345, 0)) #год, месяц, день, час, минута, секунда, день недели, день года, летнее время
'Tue Dec 10 18:07:14 2024'
>>> time.ctime(time.time())
'Mon Oct 6 20:15:03 2025'
>>> time.mktime((2025, 12, 25, 15, 30, 0, 0, 0, 0))
1766665800.0
7. Графические функции
>>> import pylab
>>> x=list(range(-3,55,4))
>>> t = list(range(15))
>>> pylab.plot(t,x)
[<matplotlib.lines.Line2D object at 0x0000017CF2E761B0>]
>>> 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 0x0000017CF50861E0>]
>>> pylab.plot(X2)
[<matplotlib.lines.Line2D object at 0x0000017CF4FE7800>]
>>> pylab.show()
Результат:
>>> region=['Центр','Урал','Сибирь','Юг']
>>> naselen=[65,12,23,17]
>>> pylab.pie(naselen,labels=region)
([<matplotlib.patches.Wedge object at 0x0000017CF4FF43B0>, <matplotlib.patches.Wedge object at 0x0000017CF4FF5730>, <matplotlib.patches.Wedge object at 0x0000017CF5579100>, <matplotlib.patches.Wedge object at 0x0000017CF5579580>], [Text(-0.191013134139045, 1.0832885038559115, 'Центр'), Text(-0.861328292412156, -0.6841882582231001, 'Урал'), Text(0.04429273995539947, -1.0991078896938387, 'Сибирь'), Text(0.9873750693480946, -0.48486129194837324, 'Юг')])
>>> pylab.show()
Результат:
>>> pylab.bar(region, naselen)
>>> pylab.title('Население по регионам')
Text(0.5, 1.0, 'Население по регионам')
>>> pylab.ylabel('Население (млн)')
Text(0, 0.5, 'Население (млн)')
>>> pylab.show()
Результат:
>>> pylab.hist(naselen)
>>> pylab.title('Гистограмма распределения населения')
>>> pylab.xlabel('Население (млн)')
>>> pylab.ylabel('Частота')
>>> 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