форкнуто от main/python-labs
Вы не можете выбрать более 25 тем
Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
367 строки
12 KiB
Markdown
367 строки
12 KiB
Markdown
# Отчет по теме 4
|
|
|
|
Девятова Мария, А-03-23
|
|
|
|
## 1 Запуск IDLE
|
|
|
|
## 2 Стандартные функции
|
|
|
|
### 2.1 Функция round
|
|
|
|
Округление числа с заданной точностью
|
|
|
|
```
|
|
a=round(123.456,1); a; type(a)
|
|
123.5
|
|
<class 'float'>
|
|
b=round(123.456,0); b; type(b)
|
|
123.0
|
|
<class 'float'>
|
|
c=round(123.456); c; type(c)
|
|
123
|
|
<class 'int'>
|
|
```
|
|
|
|
### 2.2 Функция range
|
|
|
|
Создание последовательности целых чисел с заданным шагом (по умолчанию с шагом 1).
|
|
|
|
```
|
|
gg=range(76,123,9)
|
|
gg
|
|
range(76, 123, 9)
|
|
list(gg)
|
|
[76, 85, 94, 103, 112, 121]
|
|
gg1=range(23); list(gg1)
|
|
[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
|
|
|
|
Создание общего объекта, элементами которого являются кортежи, составленные из элементов двух или более объектов-последовательностей
|
|
|
|
```
|
|
qq=['Девятова', 'Ефимова', 'Беженарь', 'Гордиевских']
|
|
ff=zip(gg,qq)
|
|
ff
|
|
<zip object at 0x000002B6596E6C00>
|
|
tuple(ff)
|
|
((76, 'Девятова'), (85, 'Ефимова'), (94, 'Беженарь'), (103, 'Гордиевских'))
|
|
ff[1]
|
|
Traceback (most recent call last):
|
|
File "<pyshell#16>", line 1, in <module>
|
|
ff[1]
|
|
TypeError: 'zip' object is not subscriptable
|
|
```
|
|
|
|
### 2.4 Функция eval
|
|
|
|
Вычисление значения выражения, записанного в виде символьной строки
|
|
|
|
```
|
|
fff=float(input('коэффициент усиления=')); dan=eval('5*fff-156')
|
|
коэффициент усиления=81
|
|
dan
|
|
249.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(-9)
|
|
9
|
|
pow(7, 3)
|
|
343
|
|
max(7, 9, 0)
|
|
9
|
|
min(-9, 0, 8)
|
|
-9
|
|
sum([1, -8, 7, 2])
|
|
2
|
|
divmod(43, 6)
|
|
(7, 1)
|
|
divmod(-43, 6)
|
|
(-8, 5)
|
|
divmod(-43, -6)
|
|
(7, -1)
|
|
len(qq)
|
|
4
|
|
length_words=map(len, qq); list(length_words)
|
|
[8, 7, 8, 11]
|
|
```
|
|
|
|
## 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
|
|
math.pi
|
|
3.141592653589793
|
|
math.degrees(1)
|
|
57.29577951308232
|
|
math.radians(60)
|
|
1.0471975511965976
|
|
math.sin(math.radians(30))
|
|
0.49999999999999994
|
|
math.degrees(math.acos(0.5))
|
|
60.00000000000001
|
|
math.degrees(math.acos(12))
|
|
Traceback (most recent call last):
|
|
File "<pyshell#70>", line 1, in <module>
|
|
math.degrees(math.acos(12))
|
|
ValueError: math domain error
|
|
math.exp(2)
|
|
7.38905609893065
|
|
math.log(math.e)
|
|
1.0
|
|
math.log(49, 7)
|
|
2.0
|
|
math.log(-49, 7)
|
|
Traceback (most recent call last):
|
|
File "<pyshell#73>", line 1, in <module>
|
|
math.log(-49, 7)
|
|
ValueError: math domain error
|
|
math.log10(10)
|
|
1.0
|
|
math.sqrt(121)
|
|
11.0
|
|
math.sqrt(-49)
|
|
Traceback (most recent call last):
|
|
File "<pyshell#79>", line 1, in <module>
|
|
math.sqrt(-49)
|
|
ValueError: math domain error
|
|
math.ceil(11/2)
|
|
6
|
|
math.floor(11/2)
|
|
5
|
|
```
|
|
|
|
## 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 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.03177690077737194
|
|
random.random()
|
|
0.42660420133444044
|
|
random.random()
|
|
0.6029016351661705
|
|
random.uniform(3, 8)
|
|
3.349556259329991
|
|
random.randint(3, 8)
|
|
7
|
|
random.gauss()
|
|
1.3115168238883617
|
|
random.gauss(5, 8)
|
|
18.723843368888335
|
|
lst=[13, 'cat', 5-8j, (1, 7), 67.8]
|
|
random.choice(lst)
|
|
(1, 7)
|
|
random.shuffle(lst)
|
|
lst
|
|
[(1, 7), 13, 'cat', (5-8j), 67.8]
|
|
random.sample(lst, 3)
|
|
['cat', 67.8, (5-8j)]
|
|
help(random.betavariate)
|
|
Help on method betavariate in module random:
|
|
|
|
betavariate(alpha, beta) method of random.Random instance
|
|
Beta distribution.
|
|
|
|
Conditions on the parameters are alpha > 0 and beta > 0.
|
|
Returned values range between 0 and 1.
|
|
|
|
The mean (expected value) and variance of the random variable are:
|
|
|
|
E[X] = alpha / (alpha + beta)
|
|
Var[X] = alpha * beta / ((alpha + beta)**2 * (alpha + beta + 1))
|
|
|
|
random.betavariate(3, 7)
|
|
0.5892004380254151
|
|
help(random.gammavariate)
|
|
Help on method gammavariate in module random:
|
|
|
|
gammavariate(alpha, beta) method of random.Random instance
|
|
Gamma distribution. Not the gamma function!
|
|
|
|
Conditions on the parameters are alpha > 0 and beta > 0.
|
|
|
|
The probability distribution function is:
|
|
|
|
x ** (alpha - 1) * math.exp(-x / beta)
|
|
pdf(x) = --------------------------------------
|
|
math.gamma(alpha) * beta ** alpha
|
|
|
|
The mean (expected value) and variance of the random variable are:
|
|
|
|
E[X] = alpha * beta
|
|
Var[X] = alpha * beta ** 2
|
|
|
|
random.gammavariate(4, 6)
|
|
21.738935796671953
|
|
rand=[random.uniform(1,2), random.gauss(), random.betavariate(2,5), random.gammavariate(3, 4)]
|
|
rand
|
|
[1.0853816485082923, -1.2263412989631917, 0.44973003958419866, 8.863321797224248]
|
|
```
|
|
|
|
## 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
|
|
1761126046.1433933
|
|
c2=time.time()-c1; c2
|
|
12.040217399597168
|
|
dat=time.gmtime(); dat
|
|
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=22, tm_hour=9, tm_min=41, tm_sec=17, tm_wday=2, tm_yday=295, tm_isdst=0)
|
|
type(dat)
|
|
<class 'time.struct_time'>
|
|
KeyboardInterrupt
|
|
dat.tm_mon
|
|
10
|
|
dat.tm_yday
|
|
295
|
|
msc=time.localtime()
|
|
msc
|
|
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=22, tm_hour=12, tm_min=43, tm_sec=12, tm_wday=2, tm_yday=295, tm_isdst=0)
|
|
time.asctime()
|
|
'Wed Oct 22 12:57:32 2025'
|
|
time.ctime()
|
|
'Wed Oct 22 12:58:08 2025'
|
|
time.sleep(5)
|
|
time.mktime(msc)
|
|
1761126192.0
|
|
time.localtime(c1)
|
|
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=22, tm_hour=12, tm_min=40, tm_sec=46, tm_wday=2, tm_yday=295, 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 0x000002B66266AD50>]
|
|
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 0x000002B664343610>]
|
|
pylab.plot(X2)
|
|
[<matplotlib.lines.Line2D object at 0x000002B664343750>]
|
|
pylab.show()
|
|
```
|
|

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

|
|
|
|
```
|
|
pylab.hist([2, 3, 4, 21, 14, 0, 13, 19, 7, 9, 11], bins=4)
|
|
(array([4., 2., 3., 2.]), array([ 0. , 5.25, 10.5 , 15.75, 21. ]), <BarContainer object of 4 artists>)
|
|
pylab.show()
|
|
```
|
|
|
|

|
|
|
|
```
|
|
pylab.bar(region, naselen)
|
|
<BarContainer object of 4 artists>
|
|
pylab.show()
|
|
```
|
|
|
|

|
|
|
|
## 8 Некоторые функции статистического модуля statistics
|
|
|
|
```
|
|
import statistics
|
|
dir(statistics)
|
|
['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']
|
|
statistics.mode(['banana', 'apple', 'strawberry', 'lemon', 'apple', 'pineapple', 'lemon', 'apple'])
|
|
'apple'
|
|
statistics.mode(['banana', 'apple', 'strawberry', 'lemon', 'apple', 'pineapple', 'lemon', 'banana'])
|
|
'banana'
|
|
statistics.correlation(X1, X2)
|
|
-0.3939192985791677
|
|
statistics.stdev(X1)
|
|
2.4083189157584592
|
|
statistics.mean(X1)
|
|
8.6
|
|
``` |