This repository has been archived by the owner on Jan 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
laba3_Coding.py
139 lines (139 loc) · 14 KB
/
laba3_Coding.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import random # подключение модуля рандом
import math
end = 1 # создание переменной для выхода из программы
while end == 1: # цикл для повторения программы
try: # обработка исключений, попытка совершить уязвимый код
change = int(input("""Меню:
1 - Задача №1
2 - Задача №2
3 - Задача №3
4 - Задача №4
0 - Выход из программы
""")) # инициализация переменной выбора + вывод меню
if change == 1: # выбор задачи 1
print("\nЗадача №1: Угадай число")
end1 = 1 # инициализация переменной для выхода из задачи
krug = 0 # инициализация переменной, считающей попытки
score = 0 # инициализация переменной, считающей количество угаданных чисел
while end1 != 0: # цикл для повторения итерации
try:
print("Попытка:" + str(krug+1))
x = int(input("Загадайте число (от 1 до 10, 0 - выход): ")) # инициализация переменной, попытка пользователя
x1 = random.randint(1,10)
krug+=1
print()
if x == x1: # если число угадали
print("Вы угадали число. Поздравляем!")
print("Попыток:" + str(krug))
score+=1
print("Ваш рекорд: " + str(score))
end1 = int(input("Для выхода введите 0, для продолжения нажмите любую другую клавишу: "))
print()
if x == 0: # если вводят 0, то итерация прерывается, открывется меню
end1=0
except: # реакция на ошибку в уязвимом коде
print("Вы ввели не целочисленное число!")
print()
print()
elif change == 2: # выбор задачи 2
print("\nЗадача №2")
def capitalize(slovo): # функция, принимает строчку
a = slovo[0].upper() # локальная переменная а, которой присвается первый символ строки, upper строковый метод, который делает все буквы заглавными
return a + slovo[1:] # функция возвращает строку, которая начинается с a,
vvod = input("Введите строку: ").split() # инициализация строкового массива (вводится строка с разделением на отдельные слова через сплит (пробел как разделитель))
vivod = []
for slovo in vvod: # цикл for, каждый элемент массива обозначает как slovo
vivod.append(capitalize(slovo)) # добавляет в новый массив слова, пройдящие через функцию
print(' '.join(vivod)) # вывод с добавлением пробела в конец каждой строки массива с помощью функции
print()
elif change == 3: # выбор задачи 3
print("\nЗадача №3")
def sortRU(mas): # функция сортировки массива расчёской по убыванию, получает на вход массив
dlina = len(mas) # инициализация переменной, отвечающий за расстояние между сортирующими началами
perekluchenie = True # инициализация булевой переменной
while dlina > 1 or perekluchenie: # цикл while выполняется пока длина между сортировщиками больше 1 или если переключение истинно
dlina = max(1, int(dlina / 1.247)) # уменьшение расстояния динны, функция max, чтобы не было < 1
perekluchenie = False # переключателю присвается false (чтобы цикл не продолжался если расстояние между сортировщиками 1 или меньше)
for i in range(len(mas) - dlina): # цикл for для i в для первого сортировщика
j = i + dlina # для второго сортировщика
if mas[i] < mas[j]: # если элемент первого сортировщика меньше второго
mas[i], mas[j] = mas[j], mas[i] # то они меняются местами
perekluchenie = True # переключателю присвается истина (чтобы цикл продолжался, если расстояние 1 и нашлись ещё элементы для сортировки)
return mas # функция возвращает массив (список) обратно
try:
N = int(input("Введите размер списка: "))
mas = []
i = 0
while i < N:
mas.append(random.randint(0,999))
i+=1
print(mas)
sortRU(mas)
print(mas)
except:
print("Вы ввели не целочисленное число!")
print()
elif change == 4: # выбор четвёртой задачи
print("\nЗадача №4")
print("""
1 2 3 4 5 6
___________
1|p h q g m j
2|e a y l n -
3|o f d x k -
4|r c v s z -
5|w b u t i -""")
dictionary = {"p":"11", "h":"12", "q":"13", "g":"14", "m":"15", "j":"16",
"e":"21", "a":"22", "y":"23", "l":"24", "n":"25",
"o":"31", "f":"32", "d":"33", "x":"34", "k":"35",
"r":"41", "c":"42", "v":"43", "s":"44", "z":"45",
"w":"51", "b":"52", "u":"53", "t":"54", "i":"55"} # словарь
dictionary2 = {"11":"p", "12":"h", "13":"q", "14":"g", "15":"m", "16":"j",
"21":"e", "22":"a", "23":"y", "24":"l", "25":"n",
"31":"o", "32":"f", "33":"d", "34":"x", "35":"k",
"41":"r", "42":"c", "43":"v", "44":"s", "45":"z",
"51":"w", "52":"b", "53":"u", "54":"t", "55":"i"}
def code(fraze): # функция для закодирования ввёдённой строки
global new_txt # глобальная переменная - строка которую по итогу увидит пользователь
list(fraze) # строку переделывают в строковый массив (каждая буква строки)
for x in fraze:
if x in dictionary: # если элемент массива есть в словаре
new_txt += dictionary.get(x) # возвращает значение элемента согласно словарю
else:
new_txt += x # в ином случае элемент просто присваивается в новую строку
return str(new_txt)
def decode(fraze): # дешифратор
global new_txt2
mas1 = list(fraze.split()) # разделение слов
for i in range (0,len(mas1)): # проход по каждому слову
mas2 = []
for t in range (0,math.floor(len(mas1[i])/2)): # второму массиву (для каждой буквы(2цифры)) изменяется размер на длинну слова попполам
mas2.append(0)
m =0
n =1
for j in range(0,len(mas2)): # присвоение элементам нового массива по 2 цифры элемента первого массива
mas2[j] = mas1[i][j+m] + mas1[i][j+n]
m = m+1
n = n+1
for k in mas2: # поиск в словаре
if k in dictionary2:
new_txt2 += dictionary2.get(k)
else:
new_txt2 += k
new_txt2 += " "
return new_txt2
new_txt = ""
new_txt2 = ""
fraze = input("Введите вашу фразу (латинскими строчными буквами): ")
code(fraze)
print(new_txt)
print(decode(new_txt))
print()
elif change == 0: # случай, если пользователь решил выйти из программы
end = 0
else: # если пользователь ввёл цифру, не соответвующюю пунктам меню
print()
continue # оператор, начинающий следующий проход цикла
except:
print("Вы ввели не целочисленное число!")
print()