Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Скачиваний:
18
Добавлен:
09.08.2021
Размер:
223.89 Кб
Скачать

Python, ПОАС, ОКЗ, ИКЗ 12 и протокол по теме 4

#Общее контрольное задание по Теме 4

>>>import cmath

kort=(math.floor(divmod(round(cmath.phase(0.2+0.8j),2)*20,3)[0]),math.floor(divmod(round(cmath.phase(0.

2+0.8j),2)*20,3)[1]))

>>>kort

(8, 2)

#Фаза 0.2+0.8j приблизительно равна 1.325, после округления до 2 знаков после запятой: 1.33. После умножения на 20 получается 26.6. Ближайшее к 26.6 число, которое без остатка делится на 3 - это число 24, 24/3=8. Остаток от деления 26.6 на 3 равен 2.6. Округленные вниз значения 8.0 и 2.6: 8 и 2.

>>>import time

>>>tt=time.localtime()

>>>tt

time.struct_time(tm_year=2020, tm_mon=10, tm_mday=13, tm_hour=20, tm_min=41, tm_sec=29, tm_wday=1, tm_yday=287, tm_isdst=0)

>>> st=str(tt.tm_hour)+' '+str(tt.tm_min)

>>>st '20 41'

>>>nd=['понедельник','вторник','среда','четверг','пятница','суббота','воскресенье']

>>>import random

>>>random.sample(nd,3)

['четверг', 'понедельник', 'воскресенье']

>>>random.choice(list(range(14,34,3)))

23

#Число 23 - выбранное случайным образом число из списка [14, 17, 20, 23, 26, 29, 32].

>>>N=round(random.gauss(15,4))

>>>N

11

>>>import string

>>>random.sample(string.ascii_letters,N) ['r', 'v', 'N', 'V', 'c', 'T', 'i', 'R', 'm', 'n', 'f']

# string.ascii_letters - строка, содержащая строчные и заглавные латинские буквы из модуля string.

>>>c1=time.time()

>>>c1

1602613155.2745016

#Определение текущего времени в секундах от начала эпохи.

>>>c2=(time.time()-c1)/60

>>>c2

0.4437228242556254

#Так как в минуте 60 секунд, определяем разность во времени в секундах между текущим временем и временем, определенным в предыдущий раз, и делим на 60 - получаем разность в минутах.

#Ответ на контрольный вопрос

#Отличия eval() и exec() состоят в следующем: eval() вычисляет значение только одного выражения, а exec() может принимать на вход несколько инструкций с кодом. eval() возвращает значение вычисленного выражения, а exec() не возвращает.

#Примеры применения eval() и exec():

>>>eval("15+3/3")

16.0

>>>exec("a=15+1; b=2")

>>>a,b

(16, 2)

1

#Индивидуальное контрольное задание № 12

>>>import random

>>>import math

sp=[random.gauss(7,math.sqrt(36)),random.gauss(7,math.sqrt(36)),random.gauss(7,math.sqrt(36)),random.ga

uss(7,math.sqrt(36)),random.gauss(7,math.sqrt(36))]

>>>sp

[11.62135619945923, 3.9627799824697902, 20.288769873893372, -1.6883832672694776, 13.358642570092243]

>>>kort=tuple(random.sample(sp,3))

>>>kort

(13.358642570092243, -1.6883832672694776, 3.9627799824697902)

>>>sp2=list([round(kort[0],2),round(kort[1],2),round(kort[2],2)])

>>>sp2

[13.36, -1.69, 3.96]

#Протокол по Теме 4

#Пункт 2.1

>>> 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,1)) <class 'float'>

>>>type(round(123.456,0)) <class 'float'>

#Результаты вычисления функции round имеют вещественный тип. Они отличаются тем, что в первом случае цифра после запятой 5 - результат округления до одной цифры после запятой, а во втором случае цифра после запятой 0 служит для указания вещественного типа.

#Пункт 2.2

>>>gg=range(76,123,9)

>>>gg

range(76, 123, 9)

>>>type(gg) <class 'range'>

>>>list(gg)

[76, 85, 94, 103, 112, 121]

>>> 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]

#В результате получился объект с шагом 1 и диапазоном целых значений от 0 до указанного, уменьшенного на 1.

#Пункт 2.3

>>>qq=['Ф','М','П','Ч']

>>>ff=zip(gg,qq)

>>>tuple(ff)

2

((76, 'Ф'), (85, 'М'), (94, 'П'), (103, 'Ч'))

#В получившемся объекте 4 элемента-кортежа.

>>> ff[0]

Traceback (most recent call last):

File "<pyshell#20>", line 1, in <module> ff[0]

TypeError: 'zip' object is not subscriptable

#Следовательно, к элементам объекта ff нельзя обрашаться по индексу.

#Пункт 2.4

>>>fff=float(input('коэффициент усиления=')); dan=eval('5*fff-156')

коэффициент усиления=3

>>>dan

-141.0

#Пункт 2.5

>>> exec(input('введите инструкции='))

введите инструкции=perem=-123.456;gg=round(abs(perem)+98,3)

>>>gg 221.456

#Пункт 2.6

>>>abs(-23.4)

23.4

#Функция abs(a) возвращает модуль числа a.

>>>pow(-2,3)

-8

#Функция pow(a,b) возвращает число a, возведенное в степень b.

>>>min([1,-2,5.7])

-2

#Функция min(a) возвращает наименьший элемент, который содержит объект a.

>>>max([1,-2,5.7])

5.7

#Функция max(a) возвращает наибольший элемент, коорый содержит объект a.

>>> sum([1,-2,5.7]) 4.7

#Функция sum(a) возвращает сумму элементов объекта a.

>>>divmod(5,2) (2, 1)

#Функция divmod(a,b) возвращает кортеж (c,d), где c - частное - результат деления a на b, d - остаток от деления a на b.

>>>len([1,2,3,'a','abc'])

5

#Функция len(a) возвращает число элементов в объекте a.

#Пункт 3

>>>import math

>>>dir(math)

['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

>>> help(math.factorial)

Help on built-in function factorial in module math:

factorial(x, /) Find x!.

3

Raise a ValueError if x is negative or non-integral.

>>>math.factorial(5)

120

#math.factorial(x) возвращает факториал числа x.

>>>help(math.sin)

Help on built-in function sin in module math:

sin(x, /)

Return the sine of x (measured in radians).

>>>math.sin(math.pi/2)

1.0

#math.sin(x) возвращает синус числа x, указанного в радианах.

>>>help(math.acos)

Help on built-in function acos in module math:

acos(x, /)

Return the arc cosine (measured in radians) of x.

>>>math.acos(0)

1.5707963267948966

#math.acos(x) возвращает значение арккосинуса x в радианах.

>>>help(math.degrees)

Help on built-in function degrees in module math:

degrees(x, /)

Convert angle x from radians to degrees.

>>>math.degrees(math.pi)

180.0

#math.degrees(x) возвращает значение x, преобразованное из радиан в градусы.

>>>help(math.radians)

Help on built-in function radians in module math:

radians(x, /)

Convert angle x from degrees to radians.

>>>math.radians(180)

3.141592653589793

#math.radians(x) возвращает значение x, преобразованное из градусов в радианы.

>>>help(math.exp)

Help on built-in function exp in module math:

exp(x, /)

Return e raised to the power of x.

>>>math.exp(2)

7.38905609893065

#math.exp(x) возвращает число e, возведенное в степень x.

>>>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.

4

If the base not specified, returns the natural logarithm (base e) of x.

>>> math.log(math.exp(1)) 1.0

>>>math.log(100,10)

2.0

#math.log(x,a) возвращает логарифм от x по основанию a; в случае, если a не указана - по основанию e.

>>>help(math.log10)

Help on built-in function log10 in module math:

log10(x, /)

Return the base 10 logarithm of x.

>>>math.log10(0.01)

-2.0

#math.log10(x) возвращает логарифм от x по основанию 10.

>>>help(math.sqrt)

Help on built-in function sqrt in module math:

sqrt(x, /)

Return the square root of x.

>>>math.sqrt(3600)

60.0

#math.sqrt(x) возвращает квадратный корень из числа x.

>>>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.4)

-3

>>>math.ceil(3.4)

4

#math.ceil(x) возвращает число x, округленное до ближайшего наибольшего целого значения.

>>>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.6)

-4

>>>math.floor(3.6)

3

#math.floor(x) возвращает число x, округленное до ближайшего наименьшего целого значения.

>>>math.pi

3.141592653589793

5

#math.pi возвращет число pi=3.14...

>>>math.sin(2*math.pi/7+23) -0.9441954223231727

#Пункт 4

>>>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']

>>> help(cmath.sqrt)

Help on built-in function sqrt in module cmath:

sqrt(z, /)

Return the square root of z.

>>>cmath.sqrt(1.2-0.5j) (1.118033988749895-0.22360679774997896j)

#cmath.sqrt(z) возвращает квадратный корень из комплексного числа z.

>>>help(cmath.phase)

Help on built-in function phase in module cmath:

phase(z, /)

Return argument, also known as the phase angle, of a complex.

>>>cmath.phase(1-0.5j) -0.4636476090008061

#cmath.phase(z) возвращает фазу комплексного числа z.

#Пункт 5

>>>import random

>>>dir(random)

['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_inst', '_itertools', '_log', '_os', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', '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 hashable object.

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()

6

# 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.8096254830717624

# random.random() возвращает равномерно распределенное случайное число.

>>>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.

>>>random.uniform(2,7)

5.113795320659702

# random.uniform(a,b) возвращает равномерно распределенное случайное число из интервала [a,b) или [a,b] в зависимости от округления.

>>>help(random.gauss)

Help on method gauss in module random:

gauss(mu, sigma) 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(1,2)

2.5850531922907862

# random.gauss(a,b) возвращает нормально распределенное случайное число в соответствии с параметрами: a - среднее, b - стандартное отклонение.

>>>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(5,7)

5

# random.randint(a,b) возвращает случайное целое число, принадлежащее отрезку [a,b].

>>>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([1,2,3,7,8,9])

7

# random.choice(a) возвращает случайный элемент из совокупности элементов a.

>>>help(random.shuffle)

7

Help on method shuffle in module random:

shuffle(x, random=None) method of random.Random instance Shuffle list x in place, and return None.

Optional argument random is a 0-argument function returning a random float in [0.0, 1.0); if it is the default None, the standard random.random will be used.

>>>a=[1,2,3,7,8,9]

>>>random.shuffle(a)

>>>a

[2, 8, 1, 9, 7, 3]

# random.shuffle(a) случайным образом переставляет элементы списка a.

>>> help(random.sample)

Help on method sample in module random:

sample(population, k) method of random.Random instance

Chooses k unique random elements from a population sequence or set.

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.

To choose a sample in a range of integers, use range as an argument. This is especially fast and space efficient for sampling from a

large population: sample(range(10000000), 60)

>>>random.sample([1,2,3,7,8,9],3) [7, 3, 9]

# random.sample(a,n) возвращает n элементов из совокупности элементов a.

>>>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.

>>>random.betavariate(1,3)

0.09239405154389799

# random.betavariate(a,b) возвращает случайное число с бета-распределением в соответствии с параметрами: a - alpha, b - beta.

>>>help(random.gammavariate)

Help on method gammavariate in module random:

gammavariate(alpha, beta) method of random.Random instance Gamma distribution. Not the gamma function!

8

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

>>>random.gammavariate(1,3)

3.0589089205018434

# random.gammavariate(a,b) возвращает случайное число с гамма-распределением в соответствии с параметрами: a - alpha, b - beta.

>>>sp=[random.uniform(2,1),random.gauss(3,2),random.betavariate(1,3),random.gammavariate(2,3)]

>>>sp

[1.2757659754972352, 0.6804023779352897, 0.2102576417502387, 10.278812454983328]

#Пункт 6

>>>import time

>>>dir(time)

['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'clock', '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']

>>> help(time.time)

Help on built-in function time in module time:

time(...)

time() -> floating point number

Return the current time in seconds since the Epoch.

Fractions of a second may be present if the system clock provides them.

# time.time() возвращает время в секундах, прошедшее с начала эпохи.

>>>c1=time.time()

>>>c1

1602607165.1835687

>>>c2=time.time()-c1

>>>c2

81.03986191749573

>>>help(time.gmtime)

Help on built-in function gmtime in module time:

gmtime(...)

gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst)

Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.

GMT). When 'seconds' is not passed in, convert the current time instead.

If the platform supports the tm_gmtoff and tm_zone, they are available as attributes only.

>>>dat=time.gmtime()

>>>dat

time.struct_time(tm_year=2020, tm_mon=10, tm_mday=13, tm_hour=16, tm_min=42, tm_sec=0, tm_wday=1, tm_yday=287, tm_isdst=0)

9

# time.gmtime() возвращает полную информацию о текущем среднеевопейском времени в виде объекта класса struct_time. time.gmtime(n) преобразует n секунд в средеевропейское время.

>>>dat.tm_mon

10

>>>dat.tm_year 2020

>>>dat.tm_mday

13

>>>dat.tm_hour

16

>>>dat.tm_min

42

>>>dat.tm_sec

0

>>>dat.tm_wday

1

>>>dat.tm_yday

287

>>>dat.tm_isdst

0

>>>help(time.localtime)

Help on built-in function localtime in module time:

localtime(...)

localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min, tm_sec,tm_wday,tm_yday,tm_isdst)

Convert seconds since the Epoch to a time tuple expressing local time.

When 'seconds' is not passed in, convert the current time instead.

>>>dat2=time.localtime()

>>>dat2

time.struct_time(tm_year=2020, tm_mon=10, tm_mday=13, tm_hour=19, tm_min=45, tm_sec=49, tm_wday=1, tm_yday=287, tm_isdst=0)

# time.localtime() возвращает полную информацию о текущем местном времени в виде объекта класса struct_time. time.localtime(n) преобразует n секунд в местное время.

>>> help(time.asctime)

Help on built-in function asctime in module time:

asctime(...) asctime([tuple]) -> string

Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.

When the time tuple is not present, current time as returned by localtime() is used.

>>>time.asctime(dat2) 'Tue Oct 13 19:45:49 2020'

# time.asctime(a) преобразует объект a, характеризующий время, класса "кортеж" в строку.

>>>help(time.ctime)

Help on built-in function ctime in module time:

ctime(...)

ctime(seconds) -> string

10

Соседние файлы в папке Лабораторные_Python