форкнуто от main/python-labs
Родитель
0cac3ffb37
Сommit
d2376df544
|
После Ширина: | Высота: | Размер: 29 KiB |
|
После Ширина: | Высота: | Размер: 29 KiB |
|
После Ширина: | Высота: | Размер: 17 KiB |
|
После Ширина: | Высота: | Размер: 19 KiB |
|
После Ширина: | Высота: | Размер: 24 KiB |
@ -0,0 +1,305 @@
|
||||
# Отчет по теме 3
|
||||
Бережков Дмитрий, А-01-23
|
||||
## 1.Начало работы, настройка текущего каталога
|
||||
```py
|
||||
>>> import os
|
||||
>>> os.chdir('C:\\MPEI\\PO_ASY\\BerezhkovGit\\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
|
||||
>>> type(round(123.456,0))
|
||||
<class 'float'>
|
||||
>>> round(123.456)
|
||||
123
|
||||
>>> type(round(123.456))
|
||||
<class '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)
|
||||
>>> 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:
|
||||
```py
|
||||
>>> qq=['Berezhkov','Stepanischev','Tabolin','Krishtul']
|
||||
>>> ff=zip(gg,qq)
|
||||
>>> fff = tuple(ff)
|
||||
>>> print(fff)
|
||||
((76, 'Berezhkov'), (85, 'Stepanischev'), (94, 'Tabolin'), (103, 'Krishtul'))
|
||||
>>> print(len(fff))
|
||||
4
|
||||
>>> len(gg), len(qq)
|
||||
(6, 4)
|
||||
>>> ff[0]
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#34>", line 1, in <module>
|
||||
ff[0]
|
||||
TypeError: 'zip' object is not subscriptable
|
||||
```
|
||||
Невозможно обратиться с указанием индекса, потому что объект является итерируемым.
|
||||
|
||||
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, divmod, len, map:
|
||||
```py
|
||||
>>> abs(-13)
|
||||
13
|
||||
>>> pow(2,4)
|
||||
16
|
||||
>>> max(42,54,33)
|
||||
54
|
||||
>>> min(1,3,5)
|
||||
1
|
||||
>>> sum([1,2,3])
|
||||
6
|
||||
>>> divmod(5,3)
|
||||
(1, 2)
|
||||
>>>
|
||||
>>> len(range(9))
|
||||
9
|
||||
>>> r = map(lambda x: round(x) * (-1), [12.1245, 14.125234, 534.222])
|
||||
>>> list(r)
|
||||
[-12, -14, -534]
|
||||
```
|
||||
## 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!.
|
||||
|
||||
Raise a ValueError if x is negative or non-integral.
|
||||
|
||||
>>> math.factorial(5)
|
||||
120
|
||||
```
|
||||
3.1 Функции sin, acos, degrees, radians, exp, log, log10, sqrt, ceil, floor, pi:
|
||||
```py
|
||||
>>> math.sin(90)
|
||||
0.8939966636005579
|
||||
>>> math.acos(0)
|
||||
1.5707963267948966
|
||||
>>> math.degrees(math.pi)
|
||||
180.0
|
||||
>>> math.radians(180)
|
||||
3.141592653589793
|
||||
>>> math.exp(4)
|
||||
54.598150033144236
|
||||
>>> math.log(10)
|
||||
2.302585092994046
|
||||
>>> math.log10(100)
|
||||
2.0
|
||||
>>> math.sqrt(16)
|
||||
4.0
|
||||
>>> math.ceil(3.14)
|
||||
4
|
||||
>>> math.floor(3.14)
|
||||
3
|
||||
>>> math.pi
|
||||
3.141592653589793
|
||||
```
|
||||
3.2 Вычисление значения функции sin(2π/7+e0.23 ):
|
||||
```py
|
||||
>>> 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()
|
||||
random.random() # вещественное число от 0.0 до 1.0
|
||||
0.022635313373460364
|
||||
random.uniform(5, 15) # вещественное число от 5.0 до 15.0
|
||||
5.363612111162993
|
||||
random.randint(1, 100) # целое число от 1 до 100
|
||||
2
|
||||
random.gauss(0, 1) # mu - среднее значение, sigma - стандартное отклонение
|
||||
0.8104264223845308
|
||||
random.choice([1, 2, 3, 4]) # случайный выбор элемента из списка, кортежа, строки и т.д.
|
||||
1
|
||||
Num = [1, 2, 3, 4]
|
||||
random.shuffle(Num)
|
||||
Num
|
||||
[2, 1, 4, 3]
|
||||
random.sample(Num, 2) # случайный выбор двух элементов из Num
|
||||
[3, 1]
|
||||
random.betavariate(2, 5) # случайное число с плавающей точкой на основе бета-распределения
|
||||
0.3506592878950909
|
||||
random.gammavariate(2, 1) # случайное число с плавающей точкой на основе гамма-распределения
|
||||
3.755676054491517
|
||||
```
|
||||
## 6. Функции из модуля time.
|
||||
```py
|
||||
>>> 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
|
||||
1761120933.7341516
|
||||
>>> c2
|
||||
5.980855703353882
|
||||
>>> dat=time.gmtime()
|
||||
>>> dat
|
||||
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=22, tm_hour=8, tm_min=16, tm_sec=5, tm_wday=2, tm_yday=295, tm_isdst=0)
|
||||
>>> dat.tm_mon
|
||||
10
|
||||
>>> time.asctime((2025, 10, 13, 20, 13, 54, 1, 345, 0)) #год, месяц, день, час, минута, секунда, день недели, день года, летнее время
|
||||
'Tue Oct 13 20:13:54 2025'
|
||||
>>> time.ctime(time.time())
|
||||
'Wed Oct 22 11:19:57 2025'
|
||||
>>> time.mktime((2025, 12, 25, 15, 30, 0, 0, 0, 0))
|
||||
1766665800.0
|
||||
```
|
||||
## 7. Графические функции.
|
||||
```py
|
||||
>>> import pylab
|
||||
>>> x=list(range(-3,55,4))
|
||||
>>> t=list(range(15))
|
||||
>>> pylab.plot(t,x) #Создание графика в оперативной памяти
|
||||
[<matplotlib.lines.Line2D object at 0x000001890FC94910>]
|
||||
>>> pylab.title('Первый график')
|
||||
Text(0.5, 1.0, 'Первый график')
|
||||
>>> pylab.xlabel('время')
|
||||
Text(0.5, 0, 'время')
|
||||
>>> pylab.ylabel('сигнал')
|
||||
Text(0, 0.5, 'сигнал')
|
||||
>>> pylab.show() #Отображение графика на экране
|
||||
```
|
||||
Отображение графика:
|
||||
<image src="figure1.png">
|
||||
|
||||
```py
|
||||
>>> X1=[12,6,8,10,7]; X2=[5,7,9,11,13]
|
||||
>>> pylab.plot(X1)
|
||||
[<matplotlib.lines.Line2D object at 0x000001890FD35450>]
|
||||
>>> pylab.plot(X2)
|
||||
[<matplotlib.lines.Line2D object at 0x000001890FD35590>]
|
||||
>>> pylab.show()
|
||||
```
|
||||
Отображение графика:
|
||||
<image src="figure2.png">
|
||||
|
||||
```py
|
||||
>>> region=['Центр','Урал','Сибирь','Юг'] #Метки для диаграммы
|
||||
>>> naselen=[65,12,23,17] # Значения для диаграммы
|
||||
>>> pylab.pie(naselen,labels=region) #Создание диаграммы в памяти
|
||||
([<matplotlib.patches.Wedge object at 0x000001890E333E00>, <matplotlib.patches.Wedge object at 0x000001890F4DF110>, <matplotlib.patches.Wedge object at 0x000001890F4DF4D0>, <matplotlib.patches.Wedge object at 0x000001890F4DF750>], [Text(-0.191013134139045, 1.0832885038559115, 'Центр'), Text(-0.861328292412156, -0.6841882582231001, 'Урал'), Text(0.04429273995539947, -1.0991078896938387, 'Сибирь'), Text(0.9873750693480946, -0.48486129194837324, 'Юг')])
|
||||
>>> pylab.show() #Отображение диаграммы
|
||||
```
|
||||
Отображение диаграммы:
|
||||
<image src="figure3.png">
|
||||
|
||||
```py
|
||||
>>> pylab.bar(region, naselen)
|
||||
<BarContainer object of 4 artists>
|
||||
>>> pylab.title('Население по регионам')
|
||||
Text(0.5, 1.0, 'Население по регионам')
|
||||
>>> pylab.ylabel('Население (млн)')
|
||||
Text(0, 0.5, 'Население (млн)')
|
||||
>>> pylab.show()
|
||||
```
|
||||
Отбражение диаграммы:
|
||||
<image src="figure4.png">
|
||||
|
||||
```py
|
||||
>>> 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.title('Гистограмма распределения населения')
|
||||
Text(0.5, 1.0, 'Гистограмма распределения населения')
|
||||
>>> pylab.xlabel('Население (млн)')
|
||||
Text(0.5, 0, 'Население (млн)')
|
||||
>>> pylab.ylabel('Частота')
|
||||
Text(0, 0.5, 'Частота')
|
||||
>>> pylab.show()
|
||||
```
|
||||
Отображение гистограммы:
|
||||
<image src="figure5.png">
|
||||
## 8. Статистический модуль statistics.
|
||||
```py
|
||||
>>> import statistics
|
||||
>>> numbers = [1,2,3,4,5,6,7,8,9]
|
||||
>>> statistics.mean(numbers)
|
||||
5
|
||||
>>> statistics.median(numbers)
|
||||
5
|
||||
>>> a = [-1,-2,-3,-4,-5,-6,-7,-8,-9]
|
||||
>>> statistics.correlation(numbers, a)
|
||||
-1.0
|
||||
```
|
||||
Загрузка…
Ссылка в новой задаче