-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
17 changed files
with
15,628 additions
and
0 deletions.
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
|
||
import collections | ||
from collections import deque | ||
graph = { | ||
'A' : ['B','C'], | ||
'B' : ['D', 'E'], | ||
'C' : ['F'], | ||
'D' : [], | ||
'E' : ['F'], | ||
'F' : [] | ||
} | ||
visited = [] # List to keep track of visited nodes. | ||
queue = [] # Initialize a queue | ||
def bfs(visited, graph, node): | ||
global queue | ||
visited.append(node) | ||
queue.append(node) | ||
while queue: | ||
s = queue.pop(0) | ||
print (s, end = " ") | ||
for neighbour in graph[s]: | ||
if neighbour not in visited: | ||
visited.append(neighbour) | ||
queue.append(neighbour) | ||
# Driver Code | ||
bfs(visited, graph, 'A') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
|
||
# Функция принимает на вход строку, которая | ||
# состоит из скобок трех типов: круглые, квадратные | ||
# и фигурные. Функция должна проверить, является ли | ||
# переданная последовательность скобок сбалансированной | ||
# или нет. Функция возвращает True, если последовательность | ||
# сбалансирована, и False – в противном случае. | ||
def is_balanced(line): | ||
# Словарь со значениями (каждой открытой скобке соответсвует ее закрытая пара) | ||
pairs = { | ||
')': '(', | ||
']': '[', | ||
'}': '{' | ||
} | ||
|
||
opened = '([{' # Список для проверки если скобка открытая | ||
stack_for_symbols = [] # Стэк, в который сверху кладем скобки и берем сверху, | ||
# если нашли ей пару | ||
result = 'True' # Конечный результат | ||
|
||
for i in range(len(line)): # Цикл перебора каждого элемента подаваемого списка line | ||
if line[i] in opened: # Если элемент одна из открытых скобок | ||
stack_for_symbols.append(line[i]) # ...то присоединим его к стэку | ||
else: # Иначе, если элемент - закрытая скобка | ||
if len(stack_for_symbols) != 0: # ...то если стэк уже имеет какие-то элементы | ||
if stack_for_symbols[-1] == pairs.get(line[i]): # то если верхний элемент стэка - открытая пара скобки | ||
stack_for_symbols.pop() # то удалим его со стэка, так как для него нашлась пара | ||
else: # иначе верхний элемент стэка - тоже закрытая скобка, это уже False | ||
break # Поэтому можно остановить цикл for | ||
else: # иначе стэк пустой и есть закрытая скообка - False | ||
stack_for_symbols = ['Х'] # Заполним стэк чем-то, так как полный стэк - False | ||
if len(stack_for_symbols) != 0: # Если стэк не пустой | ||
result = 'False' # То это - False | ||
return result == 'True' # Для решения задания требуется вывод булевого значения | ||
|
||
|
||
def test_is_balanced(): | ||
cases = { | ||
'((((((((())))))))': False, | ||
'{[()]}{{}}': True, | ||
'{[()]}{]{}}': False, | ||
'{{{((([[[]]])))}}}': True, | ||
'{}': True, | ||
'(': False, | ||
'(}': False, | ||
'(((())))[]{}': True, | ||
'((()': False, | ||
'[{}{})(]': False, | ||
'{[]{([[[[[[]]]]]])}}': True, | ||
'{[]{([[[[[[]])]]])}}': False, | ||
} | ||
for i, case in enumerate(cases.keys()): | ||
if is_balanced(case) == cases[case]: | ||
print(f'{i}: OK') | ||
else: | ||
print(f'{i}: Not OK') | ||
|
||
|
||
def main(): | ||
test_is_balanced() | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
from collections import deque | ||
|
||
|
||
# Функция bfs возвращает True, если | ||
# результат поиска в ширину элемента | ||
# desired в дереве tree, начиная с | ||
# элемента start, удачен, и False, | ||
# если нет. | ||
def bfs(tree, start, desired): | ||
# | ||
# Напишите ваш код тут | ||
# | ||
|
||
|
||
def test_bfs(): | ||
tree = { | ||
1: [2, 3, 4], | ||
2: [5, 6], | ||
3: [], | ||
4: [7, 8], | ||
5: [9, 10], | ||
6: [], | ||
7: [11, 12], | ||
8: [], | ||
9: [], | ||
10: [], | ||
11: [], | ||
12: [] | ||
} | ||
if bfs(tree, 1, 11): | ||
print('OK') | ||
if bfs(tree, 1, 6): | ||
print('OK') | ||
if bfs(tree, 2, 10): | ||
print('OK') | ||
if not bfs(tree, 2, 11): | ||
print('OK') | ||
if bfs(tree, 4, 12): | ||
print('OK') | ||
if not bfs(tree, 4, 10): | ||
print('OK') | ||
|
||
|
||
def main(): | ||
test_bfs() | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
import random | ||
|
||
|
||
# Функция bubble_sort принимает список целых чисел | ||
# data и сортирует его в порядке убывания элементов с | ||
# помощью пузырьковой сортировки. Кроме того, функция | ||
# должна посчитать количество операций (итераций цикла), | ||
# которые выполняет алгоритм, и вернуть это число вызывающей | ||
# стороне. | ||
def bubble_sort(data): | ||
counter_i = 0 | ||
counter_j = 0 | ||
|
||
for i in range(len(data)): | ||
for j in range(len(data) - counter_i - 1): | ||
if data[j] < data[j + 1]: | ||
data[j], data[j + 1] = data[j + 1], data[j] | ||
counter_j += 1 | ||
counter_i += 1 | ||
return counter_j | ||
|
||
|
||
|
||
def test_sorted(): | ||
data = [random.randint(0, 1000) for i in range(100)] | ||
print(data) | ||
data_to_sort = data.copy() | ||
bubble_sort(data_to_sort) | ||
if data_to_sort == sorted(data, reverse=True): | ||
print('OK') | ||
else: | ||
print('NOT OK') | ||
|
||
|
||
def make_observations(): | ||
size = 10 | ||
results = [] | ||
for i in range(100): | ||
data = [random.randint(0, 1000) for i in range(size)] | ||
results.append((size, bubble_sort(data))) | ||
size += 10 | ||
return results | ||
|
||
|
||
def main(): | ||
test_sorted() | ||
with open('bubble.csv', 'w') as file: | ||
file.write(f'size, iterations\n') | ||
for row in make_observations(): | ||
file.write(f'{row[0]}, {row[1]}\n') | ||
print('Done!') | ||
|
||
|
||
if __name__ == '__main__': | ||
main() | ||
|
||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
def is_balanced(line): | ||
pairs = { | ||
')': '(', | ||
']': '[', | ||
'}': '{' | ||
} | ||
opened = '([{' | ||
closed = ')]}' | ||
stack_for_symbols = [] | ||
result = 'True' | ||
print(line) | ||
|
||
|
||
for i in range(len(line)): | ||
print(line[i]) | ||
if line[i] in opened: | ||
stack_for_symbols.append(line[i]) | ||
print(stack_for_symbols) | ||
else: | ||
print('hhhhhhhhhhhhhhhhhhhhh') | ||
if len(stack_for_symbols) != 0: | ||
if stack_for_symbols[-1] == pairs.get(line[i]): | ||
stack_for_symbols.pop() | ||
print(len(stack_for_symbols)) | ||
else: | ||
print('stop') | ||
break | ||
else: | ||
stack_for_symbols = ['Х'] | ||
if len(stack_for_symbols) != 0: | ||
result = 'False' | ||
print(result, len(stack_for_symbols)) | ||
|
||
|
||
|
||
|
||
line = '{[()]}{]{}}' | ||
is_balanced(line) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
from collections import deque | ||
# Функция bfs возвращает True, если | ||
# результат поиска в ширину элемента | ||
# desired в дереве tree, начиная с | ||
# элемента start, удачен, и False, | ||
# если нет. | ||
def bfs(tree, start, desired): | ||
pairs = list(zip(tree.keys(), tree.values())) | ||
for_control = [] | ||
work_list = pairs[start -1] | ||
print(work_list) | ||
for_control = work_list[1] | ||
len_for_control = len(for_control) | ||
|
||
for i in range(len_for_control): | ||
print(for_control[i]) | ||
|
||
next = pairs[for_control[i]-1][1] | ||
#if len(for_control) != 0: | ||
|
||
if len(next) != 0: | ||
#for_control.pop(0) | ||
|
||
for_control.extend(next) | ||
print(for_control, next, i) | ||
|
||
|
||
|
||
return True | ||
|
||
|
||
|
||
def test_bfs(): | ||
tree = { | ||
1: [2, 3, 4], | ||
2: [5, 6], | ||
3: [], | ||
4: [7, 8], | ||
5: [9, 10], | ||
6: [], | ||
7: [11, 12], | ||
8: [], | ||
9: [], | ||
10: [], | ||
11: [], | ||
12: [] | ||
} | ||
if bfs(tree, 1, 11): | ||
print('OK') | ||
if bfs(tree, 1, 6): | ||
print('OK') | ||
if bfs(tree, 2, 10): | ||
print('OK') | ||
if not bfs(tree, 2, 11): | ||
print('OK') | ||
if bfs(tree, 4, 12): | ||
print('OK') | ||
if not bfs(tree, 4, 10): | ||
print('OK') | ||
|
||
|
||
def main(): | ||
test_bfs() | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
Oops, something went wrong.