форкнуто от main/python-labs
Вы не можете выбрать более 25 тем
Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
344 строки
12 KiB
Markdown
344 строки
12 KiB
Markdown
# Отчёт по теме 4
|
|
|
|
Савин Семён, А-02-23
|
|
|
|
## Пункт 2. Стандартные функции из модуля builtins.
|
|
|
|
## Пункт 2.1. Округление
|
|
|
|
```py
|
|
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
|
|
>>> round(123.456)
|
|
123
|
|
```
|
|
|
|
## Пункт 2.2. Создание последовательности
|
|
|
|
```py
|
|
>>> gg = range(76,123,9)
|
|
>>> gg
|
|
range(76, 123, 9)
|
|
>>> list(gg)
|
|
[76, 85, 94, 103, 112, 121]
|
|
>>> range(23)
|
|
range(0, 23) #шаг по умолчанию 1, от 0 до 22.
|
|
>>>
|
|
```
|
|
|
|
## Пункт 2.3. Zip
|
|
|
|
```py
|
|
>>> qq = ["Савин", "Мамакин", "Капитонов", "Симанков"]
|
|
>>> ff = zip(gg,qq)
|
|
>>> tuple(ff)
|
|
((76, 'Савин'), (85, 'Мамакин'), (94, 'Капитонов'), (103, 'Симанков'))
|
|
>>> ff[1]
|
|
Traceback (most recent call last):
|
|
File "<pyshell#11>", line 1, in <module>
|
|
ff[1]
|
|
TypeError: 'zip' object is not subscriptable #нельзя обращаться по индексу
|
|
```
|
|
|
|
## Пункт 2.4. Eval
|
|
|
|
```py
|
|
>>> fff=float(input('коэффициент усиления='))
|
|
коэффициент усиления=13
|
|
>>> dan = eval('5*fff-156')
|
|
>>> dan
|
|
-91.0
|
|
```
|
|
|
|
## Пункт 2.5. Exec
|
|
|
|
```py
|
|
>>> exec(input('введите инструкции:'))
|
|
введите инструкции:perem=-123.456;gg=round(abs(perem)+98,3)
|
|
>>> gg
|
|
221.456
|
|
>>>
|
|
```
|
|
|
|
## Пункт 2.6. Другие встроенные функции
|
|
|
|
```py
|
|
>>> hi = 6
|
|
>>> hello = pow(hi,2)
|
|
>>> hello
|
|
36
|
|
>>> help(divmod)
|
|
Help on built-in function divmod in module builtins:
|
|
|
|
divmod(x, y, /)
|
|
Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
|
|
>>> divmod(40, 13)
|
|
(3, 1)
|
|
>>> list(map(len,qq))
|
|
[5, 7, 9, 8]
|
|
```
|
|
|
|
## Пункт 3. Модуль Math.
|
|
|
|
```py
|
|
>>> import math
|
|
>>> dir(math)
|
|
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', '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', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
|
|
>>> help(math.factorial)
|
|
Help on built-in function factorial in module math:
|
|
|
|
factorial(x, /)
|
|
Find x!.
|
|
|
|
Raise a ValueError if x is negative or non-integral.
|
|
|
|
>>> math.factorial(5)
|
|
120
|
|
>>> math.sin(1565)
|
|
0.46785173260407253
|
|
>>> math.log10(200)
|
|
2.3010299956639813
|
|
>>> math.sqrt(36)
|
|
6.0
|
|
>>> 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
|
|
>>> 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.
|
|
|
|
>>> help(random.seed())
|
|
Help on NoneType object:
|
|
|
|
class NoneType(object)
|
|
| Methods defined here:
|
|
|
|
|
| __bool__(self, /)
|
|
| True if self else False
|
|
|
|
|
| __repr__(self, /)
|
|
| Return repr(self).
|
|
|
|
|
| ----------------------------------------------------------------------
|
|
| Static methods defined here:
|
|
|
|
|
| __new__(*args, **kwargs) from builtins.type
|
|
| Create and return a new object. See help(type) for accurate signature.
|
|
|
|
>>> random.seed()
|
|
>>> random.random()
|
|
0.23882613686570964
|
|
>>> random.uniform(0,1)
|
|
0.3999614707805891
|
|
>>> random.randint(0,100)
|
|
6
|
|
>>> random.gauss(2, 10)
|
|
5.707349953271636
|
|
>>> random.choice([1,2,3,4,5])
|
|
2
|
|
>>> sp = [1,2,3,4,5,6,7,8,9,10,11]
|
|
>>> random.shuffle(sp)
|
|
>>> sp
|
|
[11, 7, 5, 3, 2, 10, 9, 8, 1, 6, 4]
|
|
>>> random.sample(sp,3)
|
|
[5, 10, 3]
|
|
>>> random.betavariate(0.7,0.7)
|
|
0.7563022719328397
|
|
>>> random.gammavariate(0.89,0.89)
|
|
0.5554159983098497
|
|
>>> sp1=[random.random(), random.gauss(0.5,0.5), random.betavariate(0.5,0.5), random.gammavariate(0.5, 0.5)]
|
|
>>> sp1
|
|
[0.3367662138533899, 0.25139981537793343, 0.6382522055172093, 0.7493560082921834]
|
|
```
|
|
|
|
## Пункт 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
|
|
>>> c2
|
|
8.849342107772827
|
|
>>> data = time.gmtime()
|
|
>>> data.tm_mon
|
|
10
|
|
>>> data1 = time.localtime()
|
|
>>> data1.tm_year
|
|
2025
|
|
>>> time.asctime(data)
|
|
'Mon Oct 13 01:26:52 2025'
|
|
>>> time.ctime(123461273)
|
|
'Fri Nov 30 01:47:53 1973'
|
|
>>> time.mktime(data1)
|
|
1760318835.0
|
|
>>> time.localtime(c1)
|
|
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=13, tm_hour=4, tm_min=26, tm_sec=23, tm_wday=0, tm_yday=286, tm_isdst=0)
|
|
>>> time.localtime()
|
|
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=13, tm_hour=4, tm_min=28, tm_sec=59, tm_wday=0, tm_yday=286, tm_isdst=0)
|
|
>>>
|
|
```
|
|
|
|
## Пункт 7. Модуль Pylab
|
|
|
|
```py
|
|
>>> import pylab
|
|
>>> x = list(range(-3,55,4))
|
|
>>> t = list(range(15))
|
|
>>> pylab.plot(t,x)
|
|
[<matplotlib.lines.Line2D object at 0x0000020E0362C670>]
|
|
>>> pylab.title('Первый график')
|
|
Text(0.5, 1.0, 'Первый график')
|
|
>>> pylab.xlabel("Время")
|
|
Text(0.5, 0, 'Время')
|
|
>>> pylab.ylabel("Сигнал")
|
|
Text(0, 0.5, 'Сигнал')
|
|
>>> pylab.show()
|
|
```
|
|
|
|

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

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

|
|
|
|
```py
|
|
>>> pylab.hist(X2,5)
|
|
(array([1., 1., 1., 1., 1.]), array([ 5. , 6.6, 8.2, 9.8, 11.4, 13. ]), <BarContainer object of 5 artists>)
|
|
>>> pylab.show()
|
|
>>> pylab.hist(X1,3)
|
|
(array([2., 1., 2.]), array([ 6., 8., 10., 12.]), <BarContainer object of 3 artists>)
|
|
>>> pylab.show()
|
|
```
|
|
|
|

|
|

|
|
|
|
```py
|
|
>>> pylab.bar(X1,X2)
|
|
<BarContainer object of 5 artists>
|
|
>>> pylab.show()
|
|
```
|
|
|
|

|
|
|
|
## Пункт 8. Модуль statistics
|
|
|
|
```py
|
|
>>> import statistics as stat
|
|
>>> dir(stat)
|
|
['Counter', 'Decimal', 'Fraction', 'NormalDist', 'StatisticsError', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_coerce', '_convert', '_exact_ratio', '_fail_neg', '_find_lteq', '_find_rteq', '_isfinite', '_normal_dist_inv_cdf', '_ss', '_sum', 'bisect_left', 'bisect_right', 'erf', 'exp', 'fabs', 'fmean', 'fsum', 'geometric_mean', 'groupby', 'harmonic_mean', 'hypot', 'itemgetter', 'log', 'math', 'mean', 'median', 'median_grouped', 'median_high', 'median_low', 'mode', 'multimode', 'numbers', 'pstdev', 'pvariance', 'quantiles', 'random', 'sqrt', 'stdev', 'tau', 'variance']
|
|
>>> stattest = [1,2,65,7,4,32,1,15,45]
|
|
>>> stat.median(stattest)
|
|
7
|
|
>>> stat.mode(stattest)
|
|
1
|
|
>>> stat.mean(stattest)
|
|
19.11111111111111
|
|
>>> stat.quantiles(stattest)
|
|
[1.5, 7.0, 38.5]
|
|
>>>
|
|
```
|
|
|
|
## Общее контрольное задание
|
|
|
|
## Задание
|
|
|
|
Реализовать, записать в текстовый файл и проанализировать результаты последовательности инструкций, выполняющих следующие действия:
|
|
• Напишите и исполните единое выражение, реализующее последовательное выполнение следующих операций: вычисление фазы комплексного числа 0.2+0.8j, округление результата до двух знаков после запятой, умножение полученного значения на 20, получение кортежа из двух значений: округленное вниз значение от деления результата на 3 и остатка от этого деления.
|
|
|
|
• Создайте объект класса struct_time с временными параметрами для текущего московского времени. Создайте строку с текущим часом и минутами.
|
|
|
|
• Создайте список с элементами – названиями дней недели. Сделайте случайную выборку из этого списка с тремя днями недели.
|
|
|
|
• Напишите инструкцию случайного выбора числа из последовательности целых чисел от 14 до 32 с шагом 3.
|
|
|
|
• Сгенерируйте нормально распределенное число N с математическим ожиданием 15 и стандартным отклонением 4 и округлите его до целого значения. Создайте список с N элементами – случайно выбранными буквами латинского алфавита.
|
|
|
|
• Напишите инструкцию для определения временного интервала в минутах, прошедшего с момента предыдущего (из п.2) определения временных параметров.
|
|
|
|
|
|
## Решение
|
|
|
|
```py
|
|
>>> divmod(((round(cmath.phase(0.2+0.8j),2))*20),3)
|
|
(8.0, 2.6000000000000014)
|
|
>>> tt = time.localtime()
|
|
>>> str(tt.tm_hour) + ":" + str(tt.tm_min)
|
|
'4:48'
|
|
>>> days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
|
|
>>> random.sample(days,3)
|
|
['Wed', 'Tue', 'Thu']
|
|
>>> random.choice(range(14,32,3))
|
|
17
|
|
>>> round(random.gauss(15,4))
|
|
16
|
|
>>> random.sample(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'], round(random.gauss(15,4)))
|
|
['c', 't', 'n', 'q', 'p', 'x', 'o', 'y', 'v', 'a', 'i', 'r', 'd']
|
|
>>> (time.time() - time.mktime(tt))/60
|
|
5.181675366560618
|
|
>>>
|
|
``` |