форкнуто от main/python-labs
Родитель
6eeabd204f
Сommit
1e83bb9abd
@ -0,0 +1,542 @@
|
||||
# Отчет по теме 4
|
||||
|
||||
Лыкова Елизавета, А-01-23
|
||||
|
||||
## 1. Запуск IDLE, привязка католога, создание файла отчета.
|
||||
|
||||
```py
|
||||
import os
|
||||
os.chdir("C:\\Users\\Home\\Desktop\\python-labs\\TEMA4")
|
||||
```
|
||||
|
||||
## 2. Стандартные функции.
|
||||
|
||||
## 2.1 Функция round.
|
||||
|
||||
```py
|
||||
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
|
||||
a = round(123.456,1)
|
||||
b = round(123.456,0)
|
||||
type(a)
|
||||
<class 'float'>
|
||||
type(b)
|
||||
<class 'float'>
|
||||
c = round(123.456)
|
||||
c
|
||||
123
|
||||
type(c)
|
||||
<class 'int'>
|
||||
```
|
||||
|
||||
В первых двух случаях типы получившихся данных - float, когда во втором - int.
|
||||
|
||||
## 2.2 Функция range.
|
||||
|
||||
```py
|
||||
gg = range(76,123,9)
|
||||
gg
|
||||
range(76, 123, 9)
|
||||
list(gg)
|
||||
[76, 85, 94, 103, 112, 121]
|
||||
range(23)
|
||||
range(0, 23)
|
||||
d = range(23)
|
||||
list(d)
|
||||
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
|
||||
```
|
||||
|
||||
Диапазон начинается от нуля и заканчивается предыдущим числом заданных 23-х. Шаг - единица.
|
||||
|
||||
## 2.3 Функция zip.
|
||||
|
||||
```py
|
||||
qq = ['Лыкова','Соловьёва','Коваленко','Голощапов']
|
||||
ff = zip(gg,qq)
|
||||
tuple(ff)
|
||||
((76, 'Лыкова'), (85, 'Соловьёва'), (94, 'Коваленко'), (103, 'Голощапов'))
|
||||
print(ff[0])
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#20>", line 1, in <module>
|
||||
print(ff[0])
|
||||
TypeError: 'zip' object is not subscriptable
|
||||
tt = tuple(ff)
|
||||
tt
|
||||
((76, 'Лыкова'), (85, 'Соловьёва'), (94, 'Коваленко'), (103, 'Голощапов'))
|
||||
print(tt[1])
|
||||
(85, 'Соловьёва')
|
||||
```
|
||||
|
||||
К объекту ff можно обратиться с указанием индекса, преобразовав его в кортеж.
|
||||
|
||||
## 2.4 Функция eval.
|
||||
|
||||
```py
|
||||
fff = float(input('Коэффициент усиления='));dan = eval('5*fff-156')
|
||||
Коэффициент усиления=3
|
||||
dan
|
||||
-141.0
|
||||
```
|
||||
|
||||
## 2.5 Функция exec.
|
||||
|
||||
```py
|
||||
exec(input('Введите инструкции:'))
|
||||
Введите инструкции:perem=-123.456;gg=round(abs(perem)+98,3)
|
||||
gg
|
||||
221.456
|
||||
```
|
||||
|
||||
## 2.6 Функции abs,pow,max,min,sum,dinmod,len,map.
|
||||
|
||||
```py
|
||||
abs(-5)
|
||||
5
|
||||
abs(10-15)
|
||||
5
|
||||
#Возвращает модуль числа
|
||||
pow(2,3)
|
||||
8
|
||||
pow(5,2)
|
||||
25
|
||||
#Возводит в степень
|
||||
chis = [4,5,2,8]
|
||||
max(chis)
|
||||
8
|
||||
min(chis)
|
||||
2
|
||||
slova = ['Радуга','Яблоко','Ананас','Груша']
|
||||
max(slova)
|
||||
'Яблоко'
|
||||
min(slova)
|
||||
'Ананас'
|
||||
#Находят максимальное и минимальное значения
|
||||
sum(chis)
|
||||
19
|
||||
sum(chis,10)
|
||||
29
|
||||
#Находит сумму элементов
|
||||
divmod(10,3)
|
||||
(3, 1)
|
||||
#Находит частное и остаток от деления
|
||||
len(chis)
|
||||
4
|
||||
строка = 'Hallo!'
|
||||
len(строка)
|
||||
6
|
||||
slov = {'a':10,'b':20,'c':30}
|
||||
len(slov)
|
||||
3
|
||||
#Возвращает количество элементов в объекте
|
||||
list(map(str,chis))
|
||||
['4', '5', '2', '8']
|
||||
list(map(lambda x:x*2,chis))
|
||||
[8, 10, 4, 16]
|
||||
#Применение функции к каждому элементу последовательности
|
||||
```
|
||||
|
||||
## 3. Функции модуля math.
|
||||
|
||||
```py
|
||||
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!.
|
||||
|
||||
math.factorial(5)
|
||||
120
|
||||
help(math.sin)
|
||||
Help on built-in function sin in module math:
|
||||
|
||||
sin(x, /)
|
||||
Return the sine of x (measured in radians).
|
||||
|
||||
math.sin(1)
|
||||
0.8414709848078965
|
||||
help(math.acos)
|
||||
Help on built-in function acos in module math:
|
||||
|
||||
acos(x, /)
|
||||
Return the arc cosine (measured in radians) of x.
|
||||
|
||||
The result is between 0 and pi.
|
||||
|
||||
math.acos(0.5)
|
||||
1.0471975511965979
|
||||
help(math.degrees)
|
||||
Help on built-in function degrees in module math:
|
||||
|
||||
degrees(x, /)
|
||||
Convert angle x from radians to degrees.
|
||||
|
||||
math.degrees(45)
|
||||
2578.3100780887044
|
||||
help(math.radians)
|
||||
Help on built-in function radians in module math:
|
||||
|
||||
radians(x, /)
|
||||
Convert angle x from degrees to radians.
|
||||
|
||||
math.radians(45)
|
||||
0.7853981633974483
|
||||
help(math.exp)
|
||||
Help on built-in function exp in module math:
|
||||
|
||||
exp(x, /)
|
||||
Return e raised to the power of x.
|
||||
|
||||
math.exp(3)
|
||||
20.085536923187668
|
||||
help(math.log)
|
||||
Help on built-in function log in module math:
|
||||
|
||||
log(...)
|
||||
log(x, [base=math.e])
|
||||
Return the logarithm of x to the given base.
|
||||
|
||||
If the base is not specified, returns the natural logarithm (base e) of x.
|
||||
|
||||
math.log(4,3)
|
||||
1.2618595071429148
|
||||
help(math.log10)
|
||||
Help on built-in function log10 in module math:
|
||||
|
||||
log10(x, /)
|
||||
Return the base 10 logarithm of x.
|
||||
|
||||
math.log10(3)
|
||||
0.47712125471966244
|
||||
help(math.sqrt)
|
||||
Help on built-in function sqrt in module math:
|
||||
|
||||
sqrt(x, /)
|
||||
Return the square root of x.
|
||||
|
||||
math.sqrt(5)
|
||||
2.23606797749979
|
||||
help(math.ceil)
|
||||
Help on built-in function ceil in module math:
|
||||
|
||||
ceil(x, /)
|
||||
Return the ceiling of x as an Integral.
|
||||
|
||||
This is the smallest integer >= x.
|
||||
|
||||
math.ceil(3.2)
|
||||
4
|
||||
help(math.floor)
|
||||
Help on built-in function floor in module math:
|
||||
|
||||
floor(x, /)
|
||||
Return the floor of x as an Integral.
|
||||
|
||||
This is the largest integer <= x.
|
||||
|
||||
math.floor(3.8)
|
||||
3
|
||||
math.pi
|
||||
3.141592653589793
|
||||
math.sin((2*math.pi/7)+(math.exp(0.23)))
|
||||
0.8334902641414562
|
||||
```
|
||||
|
||||
## 4. Функции из модуля cmath.
|
||||
|
||||
```py
|
||||
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.
|
||||
|
||||
```py
|
||||
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()
|
||||
help(random.random)
|
||||
Help on built-in function random:
|
||||
|
||||
random() method of random.Random instance
|
||||
random() -> x in the interval [0, 1).
|
||||
|
||||
random.random()
|
||||
0.3783037280071182
|
||||
help(random.uniform)
|
||||
Help on method uniform in module random:
|
||||
|
||||
uniform(a, b) method of random.Random instance
|
||||
Get a random number in the range [a, b) or [a, b] depending on rounding.
|
||||
|
||||
The mean (expected value) and variance of the random variable are:
|
||||
|
||||
E[X] = (a + b) / 2
|
||||
Var[X] = (b - a) ** 2 / 12
|
||||
|
||||
random.uniform(3,5)
|
||||
4.139029942389151
|
||||
help(random.randint)
|
||||
Help on method randint in module random:
|
||||
|
||||
randint(a, b) method of random.Random instance
|
||||
Return random integer in range [a, b], including both end points.
|
||||
|
||||
random.randint(4,88)
|
||||
5
|
||||
help(random.gauss)
|
||||
Help on method gauss in module random:
|
||||
|
||||
gauss(mu=0.0, sigma=1.0) method of random.Random instance
|
||||
Gaussian distribution.
|
||||
|
||||
mu is the mean, and sigma is the standard deviation. This is
|
||||
slightly faster than the normalvariate() function.
|
||||
|
||||
Not thread-safe without a lock around calls.
|
||||
|
||||
random.gauss()
|
||||
0.11579183153210448
|
||||
help(random.choice)
|
||||
Help on method choice in module random:
|
||||
|
||||
choice(seq) method of random.Random instance
|
||||
Choose a random element from a non-empty sequence.
|
||||
random.choice(qq)
|
||||
'Лыкова'
|
||||
help(random.shuffle)
|
||||
Help on method shuffle in module random:
|
||||
|
||||
shuffle(x) method of random.Random instance
|
||||
Shuffle list x in place, and return None.
|
||||
|
||||
random.shuffle(qq)
|
||||
qq
|
||||
['Коваленко', 'Лыкова', 'Соловьёва', 'Голощапов']
|
||||
help(random.sample)
|
||||
Help on method sample in module random:
|
||||
|
||||
sample(population, k, *, counts=None) method of random.Random instance
|
||||
Chooses k unique random elements from a population sequence.
|
||||
|
||||
Returns a new list containing elements from the population while
|
||||
leaving the original population unchanged. The resulting list is
|
||||
in selection order so that all sub-slices will also be valid random
|
||||
samples. This allows raffle winners (the sample) to be partitioned
|
||||
into grand prize and second place winners (the subslices).
|
||||
|
||||
Members of the population need not be hashable or unique. If the
|
||||
population contains repeats, then each occurrence is a possible
|
||||
selection in the sample.
|
||||
|
||||
Repeated elements can be specified one at a time or with the optional
|
||||
counts parameter. For example:
|
||||
|
||||
sample(['red', 'blue'], counts=[4, 2], k=5)
|
||||
|
||||
is equivalent to:
|
||||
|
||||
sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)
|
||||
|
||||
To choose a sample from a range of integers, use range() for the
|
||||
population argument. This is especially fast and space efficient
|
||||
for sampling from a large population:
|
||||
|
||||
sample(range(10000000), 60)
|
||||
|
||||
random.sample(qq,3)
|
||||
['Соловьёва', 'Лыкова', 'Голощапов']
|
||||
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(2,5)
|
||||
0.5473034184133493
|
||||
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(2,5)
|
||||
4.616261402628337
|
||||
spis = [random.uniform(0,10),random.gauss(50,15),random.betavariate(2,5),random.gammavariate(2,5)]
|
||||
spis
|
||||
[0.21672125817392973, 25.399177937155795, 0.14356042747670408, 10.552855133080406]
|
||||
```
|
||||
|
||||
## 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()
|
||||
c2=time.time()-c1
|
||||
c1,c2
|
||||
(1761295798.980248, 5.403235197067261)
|
||||
dat=time.gmtime()
|
||||
dat
|
||||
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=24, tm_hour=8, tm_min=50, tm_sec=26, tm_wday=4, tm_yday=297, tm_isdst=0)
|
||||
dat.tm_mon
|
||||
10
|
||||
local_time = time.localtime()
|
||||
local_time
|
||||
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=24, tm_hour=11, tm_min=50, tm_sec=50, tm_wday=4, tm_yday=297, tm_isdst=0)
|
||||
print(f"Год: {local_time.tm_year}")
|
||||
Год: 2025
|
||||
c1 = time.time()
|
||||
local_struct = time.localtime(c1)
|
||||
local_struct
|
||||
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=24, tm_hour=11, tm_min=54, tm_sec=13, tm_wday=4, tm_yday=297, tm_isdst=0)
|
||||
time_str = time.asctime(local_struct)
|
||||
time_str
|
||||
'Fri Oct 24 11:54:13 2025'
|
||||
time_str2 = time.ctime(c1)
|
||||
time.sleep(2)
|
||||
seconds = time.mktime(local_struct)
|
||||
seconds
|
||||
1761296053.0
|
||||
new_struct = time.localtime(seconds)
|
||||
new_struct
|
||||
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=24, tm_hour=11, tm_min=54, tm_sec=13, tm_wday=4, tm_yday=297, tm_isdst=0)
|
||||
```
|
||||
|
||||
## 7. Графические функции.
|
||||
|
||||
```py
|
||||
import pylab
|
||||
x=list(range(-3,55,4))
|
||||
t=list(range(15))
|
||||
x
|
||||
[-3, 1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53]
|
||||
t
|
||||
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
|
||||
pylab.plot(t,x)
|
||||
[<matplotlib.lines.Line2D object at 0x000002487CE9E990>]
|
||||
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 0x000002487D263390>]
|
||||
pylab.plot(X2)
|
||||
[<matplotlib.lines.Line2D object at 0x000002487D2634D0>]
|
||||
pylab.show()
|
||||

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

|
||||
data = [1, 2, 2, 3, 3, 3, 4, 4, 5]
|
||||
pylab.hist(data,5)
|
||||
(array([1., 2., 3., 2., 1.]), array([1. , 1.8, 2.6, 3.4, 4.2, 5. ]), <BarContainer object of 5 artists>)
|
||||
pylab.show()
|
||||

|
||||
c = ['A', 'B', 'C']
|
||||
v = [10, 25, 15]
|
||||
pylab.bar(c, v)
|
||||
<BarContainer object of 3 artists>
|
||||
pylab.show()
|
||||

|
||||
```
|
||||
|
||||
## 8. Модуль statistics.
|
||||
|
||||
```py
|
||||
import statistics
|
||||
data = [1, 2, 2, 3, 3, 3, 4, 4, 5]
|
||||
sred = statistics.mean(data)
|
||||
sred
|
||||
3
|
||||
moda = statistics.mode(data)
|
||||
moda
|
||||
3
|
||||
mediana = statistics.median(data)
|
||||
mediana
|
||||
3
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Загрузка…
Ссылка в новой задаче