Best Python code snippet using slash
__init__.py
Source:__init__.py
...7def dfs(visualizer, start_vertex):8 graph = visualizer.model9 visited = [False for _ in graph.vertices]10 def _dfs(v):11 visualizer.set_description('ÐеÑеÑ
одим в веÑÑÐ¸Ð½Ñ {}'.format(v))12 visualizer.set_vertex_border_color(v, colors.BLUE)13 visualizer.next_step()14 visited[v] = True15 for edge in graph.ribs:16 u = graph.get_second_directed_vertex(edge, v)17 if u is not None:18 visualizer.set_description(19 'РаÑÑмаÑÑиваем ÑебÑо ({}, {})'.format(v, u)20 )21 visualizer.set_edge_color(edge.first_vertex.index, edge.second_vertex.index, colors.RED)22 visualizer.next_step()23 if not visited[u]:24 visualizer.set_edge_color(edge.first_vertex.index, edge.second_vertex.index, colors.GREEN_NEON)25 visualizer.set_vertex_border_color(v, colors.GREY)26 _dfs(u)27 if visualizer.description:28 text = visualizer.description.get_text()29 else:30 text = ''31 text += '\nÐозвÑаÑаемÑÑ Ð² веÑÑÐ¸Ð½Ñ {}'.format(v)32 visualizer.set_description(text)33 visualizer.set_vertex_border_color(v, colors.BLUE)34 visualizer.next_step()35 else:36 visualizer.set_description('ÐеÑÑина {} бÑла помеÑена Ñанее'.format(u))37 visualizer.set_edge_color(edge.first_vertex.index, edge.second_vertex.index, colors.GREEN_NEON)38 visualizer.next_step()39 visualizer.set_description('ÐбÑ
од из веÑÑÐ¸Ð½Ñ {} законÑилÑÑ, помеÑаем веÑÑÐ¸Ð½Ñ ÐºÐ°Ðº пÑойденнÑÑ.'.format(v))40 visualizer.set_vertex_border_color(v, colors.RED)41 _dfs(start_vertex)42 visualizer.set_description('ÐбÑ
од завеÑÑен.')43 visualizer.next_step()44 visualizer.show()45def bfs(visualizer, start_vertex):46 graph = visualizer.model47 visited = [False for _ in graph.vertices]48 def _bfs(start):49 visited[start] = True50 q = Queue()51 q.put(start)52 while not q.empty():53 v = q.get()54 visualizer.set_description('ÐеÑеÑ
одим в веÑÑÐ¸Ð½Ñ {}'.format(v))55 visualizer.set_vertex_border_color(v, colors.BLUE)56 visualizer.next_step()57 for edge in graph.ribs:58 u = graph.get_second_directed_vertex(edge, v)59 if u is not None:60 visualizer.set_description(61 'РаÑÑмаÑÑиваем ÑебÑо ({}, {})'.format(v, u)62 )63 visualizer.set_edge_color(edge.first_vertex.index, edge.second_vertex.index, colors.RED)64 visualizer.next_step()65 if not visited[u]:66 visualizer.set_description(67 'ÐеÑÑина {} не поÑеÑалаÑÑ Ñанее.\n ÐобавлÑем веÑÑÐ¸Ð½Ñ Ð² оÑеÑедÑ'.format(u)68 )69 visited[u] = True70 q.put(u)71 visualizer.set_edge_color(edge.first_vertex.index, edge.second_vertex.index, colors.GREEN_NEON)72 visualizer.set_vertex_border_color(u, colors.GREY)73 visualizer.next_step()74 else:75 visualizer.set_description('ÐеÑÑина {} бÑла помеÑена Ñанее'.format(u))76 visualizer.set_edge_color(edge.first_vertex.index, edge.second_vertex.index, colors.GREEN_NEON)77 visualizer.next_step()78 visualizer.set_vertex_border_color(v, colors.RED)79 visualizer.set_description('ÐбÑ
од из веÑÑÐ¸Ð½Ñ {} законÑилÑÑ, помеÑаем веÑÑÐ¸Ð½Ñ ÐºÐ°Ðº пÑойденнÑÑ.'.format(v))80 visualizer.next_step()81 _bfs(start_vertex)82 visualizer.set_description('ÐбÑ
од завеÑÑен.')83 visualizer.next_step()84 visualizer.show()85def components(visualizer):86 graph = visualizer.model87 visited = [False for _ in graph.vertices]88 def _bfs(start, vertex_color, edge_color):89 visited[start] = True90 q = Queue()91 q.put(start)92 while not q.empty():93 v = q.get()94 visualizer.set_description('ÐеÑеÑ
одим в веÑÑÐ¸Ð½Ñ {}.'.format(v))95 visualizer.set_vertex_border_color(v, colors.BLUE)96 visualizer.next_step()97 for edge in graph.ribs:98 u = graph.get_second_directed_vertex(edge, v)99 if u is not None:100 visualizer.set_description(101 'РаÑÑмаÑÑиваем ÑебÑо ({}, {}).'.format(v, u)102 )103 visualizer.set_edge_color(edge.first_vertex.index, edge.second_vertex.index, colors.RED)104 visualizer.next_step()105 if not visited[u]:106 visualizer.set_description(107 'ÐеÑÑина {} не поÑеÑалаÑÑ Ñанее.\n'108 'ÐобавлÑем веÑÑÐ¸Ð½Ñ Ð² оÑеÑедÑ'.format(u)109 )110 visited[u] = True111 q.put(u)112 visualizer.set_edge_color(edge.first_vertex.index, edge.second_vertex.index, edge_color)113 visualizer.set_vertex_border_color(u, colors.GREY)114 visualizer.next_step()115 else:116 visualizer.set_description('ÐеÑÑина {} бÑла помеÑена Ñанее'.format(u))117 visualizer.set_edge_color(edge.first_vertex.index, edge.second_vertex.index, edge_color)118 visualizer.next_step()119 visualizer.set_vertex_border_color(v, vertex_color)120 visualizer.set_description('ÐбÑ
од из веÑÑÐ¸Ð½Ñ {} законÑилÑÑ, помеÑаем веÑÑÐ¸Ð½Ñ ÐºÐ°Ðº пÑойденнÑÑ.'.format(v))121 visualizer.next_step()122 comp = 0123 for i in range(len(visited)):124 visualizer.set_description('ÐÑовеÑÑем веÑÑÐ¸Ð½Ñ {}'.format(i))125 visualizer.set_vertex_area_color(i, colors.GREEN_LIGHT)126 visualizer.next_step()127 if not visited[i]:128 visualizer.set_vertex_area_color(i, colors.WHITE)129 visualizer.set_description(130 'ÐеÑеÑ
одим к компоненÑе, ÑодеÑжаÑей веÑÑÐ¸Ð½Ñ {}.\n'131 'ÐÐ»Ñ Ð¿Ð¾Ð¸Ñка вÑеÑ
веÑÑин компоненÑÑ Ð¿Ñименим bfs.'.format(i)132 )133 visualizer.next_step()134 col = random.choices(colors.COLORS_LIST, k=2)135 _bfs(i, col[0], col[1])136 visualizer.set_description('ÐомпоненÑа, ÑодеÑжаÑÐ°Ñ Ð²ÐµÑÑÐ¸Ð½Ñ {} найдена'.format(i))137 visualizer.next_step()138 comp += 1139 else:140 visualizer.set_description('ÐомпоненÑа ÑвÑзноÑÑи, ÑодеÑжаÑÐ°Ñ Ð²ÐµÑÑÐ¸Ð½Ñ {} бÑла найдена Ñанее'.format(i))141 visualizer.set_vertex_area_color(i, colors.WHITE)142 visualizer.next_step()143 visualizer.set_description('ÐÑе компоненÑÑ Ð½Ð°Ð¹Ð´ÐµÐ½Ñ.')144 visualizer.next_step()145 visualizer.show()146def dijkstra(visualizer, start_vertex, finish_vertex=None):147 heap = []148 graph = visualizer.model149 for vertex in graph.vertices:150 if vertex.index != start_vertex:151 vertex.data['dist'] = MAX_DIST152 vertex.set_label('{}\n{}; -1'.format(vertex.index, 'inf'))153 else:154 vertex.data['dist'] = 0155 vertex.data['parent'] = -1156 vertex.set_label('{}\n{}; -1'.format(vertex.index, '0'))157 heapq.heappush(heap, (graph.vertices[start_vertex].data['dist'], start_vertex))158 visualizer.set_description(159 'ÐниÑииÑÑем гÑаÑ.\n'160 'ÐобавлÑем вÑем веÑÑинам кÑоме ÑÑаÑÑовой ÑаÑÑÑоÑние inf.\n'161 'ÐобавлÑем ÑÑаÑÑовÑÑ Ð²ÐµÑÑÐ¸Ð½Ñ Ð² кÑÑÑ.'162 )163 visualizer.next_step()164 while heap:165 dist, v = heapq.heappop(heap)166 if graph.vertices[v].data['dist'] != dist:167 continue168 visualizer.set_description('ÐеÑеÑ
одим в веÑÑÐ¸Ð½Ñ {}.'.format(v))169 visualizer.set_vertex_border_color(v, colors.BLUE)170 visualizer.next_step()171 for edge in graph.ribs:172 u = graph.get_second_directed_vertex(edge, v)173 weight = edge.weight or 1174 if u is not None:175 visualizer.set_description(176 'РаÑÑмаÑÑиваем ÑебÑо ({}, {})'.format(v, u)177 )178 visualizer.set_edge_color(edge.first_vertex.index, edge.second_vertex.index, colors.RED)179 visualizer.next_step()180 d = graph.vertices[u].data['dist']181 if dist + weight < d:182 visualizer.set_description(183 'Ðайден более опÑималÑнÑй пÑÑÑ Ð² веÑÑÐ¸Ð½Ñ {}.\n'184 'УÑÑанавливаем ÑаÑÑÑоÑние до веÑÑÐ¸Ð½Ñ {}'.format(u, dist + weight)185 )186 visualizer.set_vertex_label(u, '{}\n{}'.format(u, dist + weight))187 if finish_vertex:188 ver = graph.vertices[u]189 visualizer.set_vertex_label(u, '{}; {}'.format(ver.label, v))190 graph.vertices[u].data['dist'] = dist + weight191 graph.vertices[u].data['parent'] = v192 heapq.heappush(heap, (dist + weight, u))193 else:194 visualizer.set_description('Ранее бÑл найден более опÑималÑнÑй пÑÑÑ Ð² веÑÑÐ¸Ð½Ñ {}'.format(u))195 visualizer.set_edge_color(edge.first_vertex.index, edge.second_vertex.index, colors.DEFAULT)196 visualizer.next_step()197 visualizer.set_vertex_border_color(v, colors.RED)198 visualizer.set_description('ÐбÑ
од из веÑÑÐ¸Ð½Ñ {} оконÑен.'.format(v))199 visualizer.set_description('ÐÑе кÑаÑÑайÑие ÑаÑÑÑоÑÐ½Ð¸Ñ Ð½Ð°Ð¹Ð´ÐµÐ½Ñ')200 visualizer.next_step()201 if finish_vertex:202 v = graph.vertices[finish_vertex]203 if not v.data.get('parent'):204 visualizer.set_description(u'ÐÑÑи из веÑÑÐ¸Ð½Ñ {} в веÑÑÐ¸Ð½Ñ {} не ÑÑÑеÑÑвÑеÑ'.format(start_vertex, finish_vertex))205 else:206 description = 'Ðлина кÑаÑÑайÑего маÑÑÑÑÑа из веÑÑÐ¸Ð½Ñ {} в веÑÑÐ¸Ð½Ñ {} ÑоÑÑавлÑÐµÑ {}.\n'.format(207 start_vertex, finish_vertex, v.data['dist']208 )209 description += 'ÐÑÑÑ: '210 ride = [str(v.index)]211 visualizer.set_vertex_border_color(v.index, colors.ORANGE)212 while v.data['parent'] != -1:213 visualizer.set_edge_color(v.data['parent'], v.index, colors.ORANGE)214 v = graph.vertices[v.data['parent']]215 ride.append(str(v.index))216 visualizer.set_vertex_border_color(v.index, colors.ORANGE)217 description += ' -> '.join(reversed(ride))218 description += '.'219 visualizer.set_description(description)220 visualizer.next_step()221 visualizer.show()222def kruskal(visualizer):223 graph = visualizer.model224 p = [i for i in range(len(graph.vertices))]225 def find_parent(v):226 if p[v] != v:227 p[v] = find_parent(p[v])228 return p[v]229 def unite(v, u):230 v = find_parent(v)231 u = find_parent(u)232 if random.randint(0, 1):233 v, u = u, v234 p[u] = v235 sorted_ribs = sorted([[edge.weight or 1, edge.first_vertex.index, edge.second_vertex.index] for edge in graph.ribs])236 for edge in graph.ribs:237 visualizer.set_edge_color(edge.first_vertex.index, edge.second_vertex.index, colors.GREY_LIGHT)238 visualizer.set_description(239 'ÐниÑииÑÑем гÑаÑ.\n'240 'Ðобавим каждÑÑ Ð²ÐµÑÑÐ¸Ð½Ñ Ð² Ñвое множеÑÑво.'241 )242 visualizer.next_step()243 weight = 0244 for edge in sorted_ribs:245 e = graph.find_rib(edge[1], edge[2])246 v, u = edge[1], edge[2]247 visualizer.set_description('РаÑÑмоÑÑим ÑебÑо ({}, {})'.format(edge[1], edge[2]))248 visualizer.set_edge_color(edge[1], edge[2], colors.RED)249 visualizer.next_step()250 if find_parent(v) != find_parent(u):251 visualizer.set_description(252 'ÐеÑÑÐ¸Ð½Ñ {} и {} наÑ
одÑÑÑÑ Ð² ÑазнÑÑ
множеÑÑваÑ
.\n'253 'Ðобавим ÑебÑо ({}, {}) в иÑоговÑй оÑÑов.'.format(edge[1], edge[2], edge[1], edge[2])254 )255 visualizer.set_edge_color(v, u, colors.DEFAULT)256 unite(v, u)257 weight += edge[0]258 else:259 visualizer.set_description(260 'ÐеÑÑÐ¸Ð½Ñ {} и {} Ñже наÑ
одÑÑÑÑ Ð² одном множеÑÑве.'.format(edge[1], edge[2])261 )262 visualizer.set_edge_color(v, u, colors.GREY_LIGHT)263 visualizer.next_step()264 visualizer.set_description(265 'ÐлгоÑиÑм завеÑÑилÑÑ.'266 'ÐÐµÑ Ð¼Ð¸Ð½Ð¸Ð¼Ð°Ð»Ñного оÑÑовного деÑева {}.'.format(weight)267 )268 visualizer.next_step()269 visualizer.show()270def prim(visualizer):271 graph = visualizer.model272 n = len(graph.vertices)273 visited = [False for _ in range(n)]274 min_len = [MAX_DIST for _ in range(n)]275 parent = [-1 for _ in range(n)]276 min_len[0] = 0277 answer = 0278 for edge in graph.ribs:279 visualizer.set_edge_color(edge.first_vertex.index, edge.second_vertex.index, colors.GREY_LIGHT)280 for vertex in graph.vertices:281 visualizer.set_vertex_border_color(vertex.index, colors.GREY_LIGHT)282 if vertex.index != 0:283 vertex.set_label('{}\n{}; {}'.format(vertex.index, 'inf', -1))284 else:285 vertex.set_label('0\n0; -1')286 visualizer.set_description('ÐаÑнем визÑализаÑÐ¸Ñ Ð°Ð»Ð³Ð¾ÑиÑма ÐÑима')287 visualizer.next_step()288 for _ in range(n):289 v = -1290 visualizer.set_description('Ðайдем непомеÑеннÑÑ Ð²ÐµÑÑÐ¸Ð½Ñ Ñ Ð¾Ð¿Ñеделенной минималÑной длиной')291 visualizer.next_step()292 for i in range(n):293 visualizer.set_description('РаÑÑмоÑÑим веÑÑÐ¸Ð½Ñ {}'.format(i))294 visualizer.set_vertex_border_color(i, colors.RED)295 visualizer.next_step()296 if not visited[i]:297 if (v == -1 or min_len[i] < min_len[v]):298 if v == -1:299 visualizer.set_description('Ðа ÑÑой иÑеÑаÑии ÑанÑÑе не вÑбиÑалаÑÑ Ð²ÐµÑÑина Ð´Ð»Ñ Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ, '300 'вÑбеÑем веÑÑÐ¸Ð½Ñ {}'.format(i))301 else:302 visualizer.set_description('ÐеÑÑина {} опÑималÑнее веÑÑÐ¸Ð½Ñ {}, помеÑим еÑ'.format(v, i))303 visualizer.set_vertex_border_color(v, colors.GREY_LIGHT)304 visualizer.set_vertex_border_color(i, colors.GREEN)305 v = i306 elif min_len[i] == MAX_DIST:307 visualizer.set_description('ÐеÑÑина {} не ÑвÑзана Ñ Ð²ÐµÑÑинами, помеÑеннÑми Ñанее'.format(i))308 visualizer.set_vertex_border_color(i, colors.GREY_LIGHT)309 else:310 visualizer.set_description('УвÑ, веÑÑина {} не опÑималÑна на ÑÑой иÑеÑаÑии'.format(i))311 visualizer.set_vertex_border_color(i, colors.GREY_LIGHT)312 else:313 visualizer.set_description('ÐеÑÑина {} Ñже помеÑена'.format(i))314 visualizer.set_vertex_border_color(i, colors.DEFAULT)315 visualizer.next_step()316 visited[v] = True317 answer += min_len[v]318 text = 'Ðобавим веÑÑÐ¸Ð½Ñ {} в иÑоговое минималÑное оÑÑовное деÑево'.format(v)319 visualizer.set_vertex_border_color(v, colors.DEFAULT)320 if parent[v] != -1:321 text += '\nÐобавим ÑебÑо ({}, {}) в иÑоговое минималÑное оÑÑовное деÑево'.format(v, parent[v])322 visualizer.set_edge_color(parent[v], v, colors.DEFAULT)323 visualizer.set_description(text)324 visualizer.next_step()325 visualizer.set_description('Ðбновим минималÑнÑе Ð´Ð»Ð¸Ð½Ñ Ð¸ ÑодиÑелей Ð´Ð»Ñ Ð½ÐµÐ¿Ð¾ÑеÑеннÑÑ
веÑÑин')326 visualizer.next_step()327 for u in range(n):328 edge = graph.find_rib(v, u)329 if edge:330 visualizer.set_description('РаÑÑмоÑÑим ÑебÑо ({}, {})'.format(v, u))331 visualizer.next_step()332 if visited[u]:333 visualizer.set_description('ÐеÑÑина {} Ñже помеÑена'.format(u))334 visualizer.next_step()335 elif (edge.weight or 1) < min_len[u]:336 visualizer.set_description('ÐпÑимизиÑÑем минималÑное ÑаÑÑÑоÑние Ð´Ð»Ñ Ð²ÐµÑÑÐ¸Ð½Ñ {}'.format(u))337 vertex = graph.vertices[u]338 min_len[u] = edge.weight or 1339 parent[u] = v340 vertex.set_label('{}\n{}; {}'.format(u, min_len[u], parent[u]))341 visualizer.next_step()342 else:343 visualizer.set_description('ÐеÑÑина Ñже Ð¸Ð¼ÐµÐµÑ Ð±Ð¾Ð»ÐµÐµ опÑималÑного пÑедка')344 visualizer.next_step()345 visualizer.set_description(346 'ÐлгоÑиÑм завеÑÑилÑÑ.'347 'ÐÐµÑ Ð¼Ð¸Ð½Ð¸Ð¼Ð°Ð»Ñного оÑÑовного деÑева {}.'.format(answer)348 )349 visualizer.next_step()350 visualizer.show()351def dinic(visualizer, s, t):352 graph = visualizer.model353 new_ribs = []354 def add_edge(edge):355 edge.first_vertex.data['ribs'].append(len(new_ribs))356 new_ribs.append(Edge(edge.first_vertex, edge.second_vertex, is_directed=True, max_flow=edge.max_flow))357 edge.second_vertex.data['ribs'].append(len(new_ribs))358 new_ribs.append(Edge(edge.second_vertex, edge.first_vertex, is_directed=True, max_flow=0))359 visualizer.set_description('ÐаÑнем алгоÑиÑм ÐиниÑа')360 visualizer.next_step()361 visualizer.set_description('ÐоÑÑÑоим оÑÑаÑоÑнÑÑ ÑеÑÑ Ð´Ð»Ñ Ð³ÑаÑа')362 n = len(graph.ribs)363 for vertex in graph.vertices:364 vertex.data['ribs'] = []365 vertex.data['pointer'] = 0366 for i in range(n):367 add_edge(graph.ribs[i])368 graph.ribs = new_ribs369 visualizer.next_step()370 def _fetch_pointer():371 for vertex in graph.vertices:372 vertex.data['pointer'] = 0373 def _bfs(d):374 q = Queue()375 q.put(s)376 n = len(graph.vertices)377 d[s] = 0378 for vertex in graph.vertices:379 vertex.set_label('{}\n{}'.format(vertex.index, d[vertex.index]))380 visualizer.set_description('УÑÑановим ÑаÑÑÑоÑние 0 Ð´Ð»Ñ ÑÑока, занеÑем ÑÑок в оÑеÑедÑ')381 visualizer.next_step()382 while not q.empty():383 v = q.get()384 visualizer.set_description('РаÑÑмоÑÑим веÑÑÐ¸Ð½Ñ {}'.format(v))385 visualizer.set_vertex_border_color(v, colors.RED)386 visualizer.next_step()387 for u in range(n):388 edge = graph.find_rib(v, u)389 if edge:390 visualizer.set_description('РаÑÑмоÑÑим ÑебÑо ({}, {})'.format(v, u))391 visualizer.set_edge_color(v, u, colors.RED)392 visualizer.next_step()393 if edge.current_flow == edge.max_flow:394 visualizer.set_description('ÐоÑок ÑебÑа ({}, {}) Ñже макÑимален'.format(v, u))395 visualizer.next_step()396 elif d[u] != -1:397 visualizer.set_description('ÐÐ»Ñ Ð²ÐµÑÑÐ¸Ð½Ñ {} Ñже найдено кÑаÑÑайÑее ÑаÑÑÑоÑние'.format(u))398 visualizer.next_step()399 else:400 visualizer.set_description('УÑÑанавливаем ÑаÑÑÑоÑние к веÑÑине {}\nÐобавлÑем ÐµÑ Ð² оÑеÑедÑ'.format(u))401 q.put(u)402 d[u] = d[v] + 1403 graph.vertices[u].set_label('{}\n{}'.format(u, d[u]))404 visualizer.set_vertex_border_color(u, colors.GREY)405 visualizer.next_step()406 visualizer.set_edge_color(v, u, colors.DEFAULT)407 visualizer.set_description('ÐбÑ
од Ð´Ð»Ñ Ð²ÐµÑÑÐ¸Ð½Ñ {} законÑен'.format(v))408 visualizer.set_vertex_border_color(v, colors.DEFAULT)409 visualizer.next_step()410 return d[t] != -1411 def _dfs(v, flow, d):412 visualizer.set_description('ÐеÑеÑ
одим в веÑÑÐ¸Ð½Ñ {}'.format(v))413 visualizer.set_vertex_border_color(v, colors.RED)414 visualizer.next_step()415 if not flow:416 visualizer.set_description('УвелиÑиваÑÑий поÑок из данной веÑÑÐ¸Ð½Ñ Ð½Ðµ найден')417 visualizer.set_vertex_border_color(v, colors.DEFAULT)418 visualizer.next_step()419 return 0420 if v == t:421 visualizer.set_description('Ðайден ÑвелиÑиваÑÑий поÑок велиÑÐ¸Ð½Ñ {}'.format(flow))422 visualizer.set_vertex_border_color(v, colors.DEFAULT)423 visualizer.next_step()424 return flow425 vertex = graph.vertices[v]426 while vertex.data['pointer'] < len(vertex.data['ribs']):427 id = vertex.data['ribs'][vertex.data['pointer']]428 u = graph.ribs[id].second_vertex.index429 vertex.data['pointer'] += 1430 if d[u] != d[v] + 1:431 continue432 visualizer.set_description('РаÑÑмоÑÑим ÑебÑо ({}, {})'.format(v, u))433 visualizer.set_edge_color(v, u, colors.RED)434 visualizer.next_step()435 pushed = _dfs(u, min(flow, graph.ribs[id].max_flow - graph.ribs[id].current_flow), d)436 visualizer.set_edge_color(v, u, colors.DEFAULT)437 visualizer.set_description('ÐозвÑаÑаемÑÑ Ð² веÑÑÐ¸Ð½Ñ {}'.format(v))438 visualizer.next_step()439 if pushed:440 visualizer.set_description('ÐÑибавим ÑебÑÑ ({v}, {u}) поÑок велиÑÐ¸Ð½Ñ {flow}\n'441 'СооÑвеÑÑÑвенно, оÑнимем поÑок ÑÑой же велиÑÐ¸Ð½Ñ Ñ ÑебÑе ({u}, {v})'.format(v=v, u=u, flow=pushed)442 )443 visualizer.set_vertex_border_color(v, colors.DEFAULT)444 graph.ribs[id].current_flow += pushed445 graph.ribs[id ^ 1].current_flow -= pushed446 visualizer.next_step()447 return pushed448 visualizer.set_vertex_border_color(v, colors.DEFAULT)449 visualizer.set_description('ÐбÑ
од Ð´Ð»Ñ Ð²ÐµÑÑÐ¸Ð½Ñ {} завеÑÑен, ÑвелиÑиваÑÑий поÑок не найден'.format(v))450 visualizer.next_step()451 def _dinic():452 flow = 0453 d = [-1 for _ in range(len(graph.vertices))]454 visualizer.set_description('ÐоÑÑÑоим ÑлоиÑÑÑÑ ÑеÑÑ Ð´Ð»Ñ Ð¾ÑÑаÑоÑной ÑеÑи')455 visualizer.next_step()456 while _bfs(d):457 visualizer.set_description('СлоиÑÑÐ°Ñ ÑеÑÑ Ð½Ð°Ð¹Ð´ÐµÐ½Ð°, пеÑейдем к поиÑÐºÑ Ð±Ð»Ð¾ÐºÐ¸ÑÑÑÑего поÑока')458 for edge in graph.ribs:459 if d[edge.second_vertex.index] != d[edge.first_vertex.index] + 1:460 visualizer.set_edge_color(edge.first_vertex.index, edge.second_vertex.index, colors.GREY)461 visualizer.next_step()462 _fetch_pointer()463 pushed = 1464 while pushed:465 pushed = _dfs(s, MAX_DIST, d)466 if pushed:467 flow += pushed468 visualizer.set_description('ÐÑеÑаÑÐ¸Ñ Ð·Ð°Ð²ÐµÑÑена, ÑекÑÑий поÑок {}'.format(flow))469 for edge in graph.ribs:470 visualizer.set_edge_color(edge.first_vertex.index, edge.second_vertex.index, colors.DEFAULT)471 visualizer.next_step()472 d = [-1 for _ in range(len(graph.vertices))]473 visualizer.set_description('ÐÐ»Ñ Ð´Ð°Ð½Ð½Ð¾Ð¹ ÑеÑи не ÑÑÑеÑÑвÑÐµÑ ÑлоиÑÑой ÑеÑи')474 visualizer.next_step()475 return flow476 flow = _dinic()477 new_ribs = []478 for i in range(0, len(graph.ribs), 2):479 new_ribs.append(graph.ribs[i])480 graph.ribs = new_ribs481 for edge in graph.ribs:482 if edge.current_flow > 0:483 edge.set_color(colors.BLUE)484 edge.first_vertex.set_color(colors.BLUE)485 edge.second_vertex.set_color(colors.BLUE)486 else:487 edge.set_color(colors.DEFAULT)488 visualizer.set_description('ÐлгоÑиÑм завеÑÑен. ÐелиÑина макÑималÑного поÑока - {}'.format(flow))489 visualizer.next_step()490 visualizer.show()491def min_cost_max_flow(visualizer, s, t, k=None):492 graph = visualizer.model493 new_ribs = []494 def add_edge(edge):495 edge.first_vertex.data['ribs'].append(len(new_ribs))496 ind = len(new_ribs)497 new_ribs.append(Edge(498 edge.first_vertex, edge.second_vertex, weight=edge.weight, is_directed=True, max_flow=edge.max_flow499 ))500 new_ribs[-1].data['index'] = ind + 1501 edge.second_vertex.data['ribs'].append(len(new_ribs))502 new_ribs.append(Edge(503 edge.second_vertex, edge.first_vertex, weight=-edge.weight, is_directed=True, max_flow=0504 ))505 new_ribs[-1].data['index'] = ind506 if k:507 text = 'ÐаÑнем поиÑк поÑока велиÑÐ¸Ð½Ñ {} минималÑной ÑÑоимоÑÑи'.format(k)508 else:509 text = 'ÐаÑнем поиÑк макÑималÑного поÑока минималÑной ÑÑоимоÑÑи'510 visualizer.set_description(text)511 visualizer.next_step()512 visualizer.set_description('ÐоÑÑÑоим гÑÐ°Ñ Ñ Ð¾Ð±ÑаÑнÑми ÑебÑами')513 n = len(graph.ribs)514 for vertex in graph.vertices:515 vertex.data['ribs'] = []516 vertex.data['pointer'] = 0517 for i in range(n):518 add_edge(graph.ribs[i])519 graph.ribs = new_ribs520 visualizer.next_step()521 def _min_cost_max_flow():522 flow = 0523 cost = 0524 while True:525 visualizer.set_description('ÐоÑÑÑоим оÑÑаÑоÑнÑÑ ÑеÑÑ')526 for edge in graph.ribs:527 if edge.current_flow == edge.max_flow:528 visualizer.set_edge_color(edge.first_vertex.index, edge.second_vertex.index, colors.GREY)529 else:530 visualizer.set_edge_color(edge.first_vertex.index, edge.second_vertex.index, colors.DEFAULT)531 visualizer.next_step()532 dist = [MAX_DIST for _ in range(len(graph.vertices))]533 dist[s] = 0534 heap = []535 heapq.heappush(heap, (dist[s], s))536 parent = [-1 for _ in range(len(graph.vertices))]537 visualizer.set_description('Ðайдем кÑаÑÑайÑее ÑаÑÑÑоÑÐ½Ð¸Ñ Ð¸Ð· ÑÑока в иÑÑок')538 visualizer.next_step()539 while heap:540 d, v = heapq.heappop(heap)541 if d != dist[v]:542 continue543 visualizer.set_description('РаÑÑмоÑÑим веÑÑÐ¸Ð½Ñ {}'.format(v))544 visualizer.set_vertex_border_color(v, colors.RED)545 visualizer.next_step()546 for edge in graph.ribs:547 if edge.first_vertex.index == v:548 u = edge.second_vertex.index549 if edge.current_flow < edge.max_flow:550 visualizer.set_description('РаÑÑмоÑÑим ÑебÑо ({}, {})'.format(v, u))551 visualizer.set_edge_color(v, u, colors.RED)552 visualizer.next_step()553 if dist[v] + edge.weight < dist[u]:554 visualizer.set_description(555 'ÐбновлÑем кÑаÑÑайÑее ÑаÑÑÑоÑние, а Ñак же ÑодиÑÐµÐ»Ñ Ð´Ð»Ñ Ð²ÐµÑÑÐ¸Ð½Ñ {}'.format(u)556 )557 visualizer.set_vertex_border_color(u, colors.TURQUOISE)558 dist[u] = dist[v] + edge.weight559 parent[u] = v560 ver = graph.vertices[u]561 ver.set_label('{}\n{}; {}'.format(ver.index, dist[u], parent[u]))562 heapq.heappush(heap, (dist[u], u))563 visualizer.next_step()564 else:565 visualizer.set_description('ÐÐ»Ñ Ð²ÐµÑÑÐ¸Ð½Ñ {} Ñже найдено более опÑималÑное ÑаÑÑÑоÑние'.format(u))566 visualizer.next_step()567 visualizer.set_edge_color(v, u, colors.DEFAULT)568 visualizer.set_description('ÐбÑ
од из веÑÑÐ¸Ð½Ñ {} завеÑÑен'.format(v))569 visualizer.set_vertex_border_color(v, colors.DEFAULT)570 visualizer.next_step()571 if parent[t] == -1:572 visualizer.set_description('ÐÑÑÑ Ð¸Ð· иÑÑока в ÑÑок не найден')573 visualizer.next_step()574 return flow, cost575 addflow = k - flow if k else MAX_DIST576 cur_v = t577 while cur_v != s:578 visualizer.set_vertex_border_color(cur_v, colors.BLUE)579 visualizer.set_edge_color(parent[cur_v], cur_v, colors.BLUE)580 edge = graph.find_rib(parent[cur_v], cur_v)581 addflow = min(addflow, edge.max_flow - edge.current_flow)582 cur_v = parent[cur_v]583 visualizer.set_vertex_border_color(cur_v, colors.BLUE)584 visualizer.set_description('Ðайден пÑÑÑ Ð¸Ð· иÑÑока в ÑÑок, пÑибавим поÑок велиÑÐ¸Ð½Ñ {} Ð´Ð»Ñ ÐµÐ³Ð¾ ÑебеÑ'.format(addflow))585 visualizer.next_step()586 cur_v = t587 while cur_v != s:588 edge = graph.find_rib(parent[cur_v], cur_v)589 edge.current_flow += addflow590 graph.ribs[edge.data['index']].current_flow -= addflow591 cost += addflow * edge.weight592 cur_v = parent[cur_v]593 flow += addflow594 cur_v = t595 while cur_v != s:596 visualizer.set_vertex_border_color(cur_v, colors.DEFAULT)597 visualizer.set_edge_color(parent[cur_v], cur_v, colors.DEFAULT)598 cur_v = parent[cur_v]599 visualizer.set_vertex_border_color(cur_v, colors.DEFAULT)600 if k and flow == k:601 visualizer.set_description('ÐоÑок велиÑÐ¸Ð½Ñ {} найден'.format(k))602 visualizer.next_step()603 return flow, cost604 visualizer.set_description('ÐÑеÑаÑÐ¸Ñ Ð·Ð°Ð²ÐµÑÑена, ÑекÑÑий поÑок - {}, ÑÑоимоÑÑÑ - {}'.format(flow, cost))605 visualizer.next_step()606 flow, cost = _min_cost_max_flow()607 new_ribs = []608 for i in range(0, len(graph.ribs), 2):609 new_ribs.append(graph.ribs[i])610 graph.ribs = new_ribs611 for edge in graph.ribs:612 if edge.current_flow > 0:613 edge.set_color(colors.BLUE)614 edge.first_vertex.set_color(colors.BLUE)615 edge.second_vertex.set_color(colors.BLUE)616 else:617 edge.set_color(colors.DEFAULT)618 for vertex in graph.vertices:619 vertex.set_label(vertex.index)620 visualizer.set_description('ÐлгоÑиÑм завеÑÑен. Ðайден поÑок велиÑÐ¸Ð½Ñ {} ÑÑоимоÑÑи {}'.format(flow, cost))621 visualizer.next_step()622 visualizer.show()623ALGORITHMS = {624 'dfs': dfs,625 'bfs': bfs,626 'components': components,627 'dijkstra': dijkstra,628 'kruskal': kruskal,629 'prim': prim,630 'dinic': dinic,631 'min_cost_max_flow': min_cost_max_flow...
main.py
Source:main.py
2from Items import Item3from time import sleep4# Kitchen5kitchen = Room("kitchen")6kitchen.set_description("""7The Kitchen8-----------------------------9A small bright room, there is a cooker beside the door, 10and a sink under one window, opposite the door a second window overlooks the garden.11Everything is bright and light, the linoleum is yellow, the cupboards are cream,12the trims are blue""")13# Things in the Kitchen14# White Goods, sort of15kettle = Item("kettle")16kettle.set_description("A cream coloured electric kettle, useful for boiling water")17cooker = Item("cooker")18cooker.set_description("A white gas cooker with 4 rings on the hob and a grill at the top. Good for cooking on.")19# Cutlery, plates etc20mug = Item("mug")21mug.set_description("A mug for drinking out of, it commemorates the death of Princess Diana")22plate = Item("plate")23plate.set_description("A white ceramic plate with a blue rim, slightly chipped")24knife = Item("Knife")25knife.set_description("A table knife, good for spreading, less good for stabbing")26fork = Item("fork")27fork.set_description("An ordinary fork, for eating with, or in a pinch for whisking")28tea_spoon = Item("tea spoon")29tea_spoon.set_description("A spoon for small jobs, like fishing tea bags out of a mug")30spoon = Item("spoon")31spoon.set_description("A regular desert spoon, the sort you might eat cereal with.")32# Pen and Paper33newspaper = Item("newspaper")34newspaper.set_description("""35A newspaper, headlines on the front, sports on the back, mostly news in the middle,36the crossword is near the end""")37biro = Item("biro")38biro.set_description("A useful pen for making notes, or doing the crossword with. Mightier than a sword?")39# Fridge and Contents40fridge = Item("fridge")41fridge.set_description("""42A cold storage for the kind of things you keep in a kitchen. Milk, some orange juice, some cheese, 43half a jar of strawberry jam of unknown origin, some mustard that might possible predate decimal currency.""")44milk = Item("milk")45milk.set_description("A bottle of milk, half full. Or half empty, depending on how you think")46jam = Item("jam")47jam.set_description("Half a jar of strawberry jam, provenance unknown")48mustard = Item("mustard")49mustard.set_description("""50The remains of some very old mustard, a very lurid shade of yellow. 51Smells firey, like it might take your nose hairs""")52cheese = Item("cheese")53cheese.set_description("Some regular yellow cheese, a small bit. The kind mice are supposed to like. A good snack.")54# Furniture55kitchen_table = Item("kitchen table")56kitchen_table.set_description("A small wooden table with painted white legs and top")57kitchen_chair = Item("kitchen chair")58kitchen_chair.set_description(" A painted white chair with a yellow seat cushion. One of a pair.")59kitchen_window = Item("kitchen window")60kitchen_window.set_description("A window, you can see the garden out of it.")61# Bedroom62bedroom = Room("bedroom")63bedroom.set_description("""64The Bedroom 65----------------------------66The walls are blue, there is a table with a lamp on it on either side of67the bed on the east wall. On one side, there is a small stack of books and an alarm clock. 68The furniture is pine, the curtains are darker blue and match the carpet.69There is a pine chest of drawers against the west wall.70""")71# Things in the Bedroom72# Furniture73bed = Item("bed")74bed.set_description("An orange pine frame double bed, the coverlet and pillows are blue")75side_table_books = Item("side table with books on")76side_table_books.set_description("A side table with a small stack of books on")77side_table_empty = Item("side table without books on")78side_table_empty.set_description("A side table with nothing on it, no one uses this side of the bed regularly")79chest_of_drawers = Item("chest of drawers")80chest_of_drawers.set_description("A chest of five drawers, orange pine. For storing clothes in. A hairbrush is on top.")81curtains = Item("curtains")82curtains.set_description("Dark blue curtains to keep the daylight out")83bedroom_window = Item("bedroom window")84bedroom_window.set_description("A window, you can see the garden out of it.")85# Small Objects86alarm_clock = Item("alarm clock")87alarm_clock.set_description("""88A small battery powered alarmclock, silver, with what looks like glow in the dark paint on the hands.""")89table_lamp = Item("lamp")90table_lamp.set_description("A side lamp for reading by in bed")91top_book = Item("top book")92top_book.set_description("The top book in the stack, its not written in a recognisable language")93second_book = Item("second book")94second_book.set_description("""95A copy of Charles Dickens Great Expectations, there's a bookmark two thirds of the way through""")96bottom_book = Item("bottom_book")97bottom_book.set_description("A copy of War and Peace, but it doesn't look like it's ever been opened.")98hairbrush = Item("hairbrush")99hairbrush.set_description("A black plastic hairbrush with white spikes. For brushing hair.")100# Clothes101pyjamas = Item("pyjamas")102pyjamas.set_description("Pyjamas, for sleeping in.")103underwear = Item("underwear")104underwear.set_description("""105It's what you wear under your clothes. You could go without it, but that sort of thing tends to be frowned upon.""")106shirt = Item("shirt")107shirt.set_description("A clean shirt to wear, it's pale blue, that's nice")108trousers = Item("trousers")109trousers.set_description("Clean trousers to wear, they're dark green")110jumper = Item("jumper")111jumper.set_description("A nice navy blue jumper that someone knitted, it smells very faintly of lemons.")112# Hall113hall = Room("hall")114hall.set_description("""115The Hall116------------------------------117There is not much natural light in here. Some comes through the glass panels118in the front door. There is a coat stand on the east wall, there is a key hook 119on the west wall. At the southern end you can see the kitchen. A door on the east wall leads to the bedroom,120a door on the west wall leads to the bathroom.121""")122# Things in the Hall123coat_stand_dict = {"look": """124A wooden stand for hanging coats on, maybe hats and scarves too. You can put umbrellas in the base125""", "use" : " You hang your jacket on the coat stand"}126coat_stand = Item("coat stand", coat_stand_dict)127# coat_stand.set_description({"look": """128# A wooden stand for hanging coats on, maybe hats and scarves too. You can put umbrellas in the base129# """, "use" : " You hang your jacket on the coat stand"})130key_hook = Item("key hook")131key_hook.set_description("Hooks for hanging keys on, there's a spare set here for the front door.")132door_mat = Item("door mat")133door_mat.set_description("A scratchy brown mat for getting the dirt off your shoes when you come in")134# Bathroom135bathroom = Room("bathroom")136bathroom.set_description("""137The Bathroom138--------------------------139This room is white. There is a toilet and a sink and a bathtub with a shower. 140The shower curtain is also white, and is slightly mouldy at the base. The glass 141in the window is frosted. There is a mirrored cabinet above the sink. There is142a towel on the radiator.143""")144# Things in the Bathroom145# Fixtures and Fittings146bathtub = Item("bathtub")147bathtub.set_description("A regular white ceramic bathtub, the sort with silver handles in the sides to help you stand")148shower_curtain = Item("shower curtain")149shower_curtain.set_description("A white shower curtain to keep the water inside the tub, slightly mouldy.")150sink = Item("sink")151sink.set_description("A white ceramic sink for washing your hands and brushing your teeth, that sort of thing.")152toilet = Item("toilet")153toilet.set_description("A toilet, white with a plastic seat. Could probably use a scrub.")154mirrored_cabinet = Item("mirrored cabinet")155mirrored_cabinet.set_description("A mirrored cabinet for storing things in, look into it and see your reflection")156bathroom_window = Item("bathroom window")157bathroom_window.set_description("A frosted window, you can't see out of it.")158# In the Cabinet159tooth_mug = Item("tooth mug")160tooth_mug.set_description("""161A slightly chipped tooth mug, white ceramic with a blue rim, looks like it matches the kitchen plate""")162toothbrush = Item("toothbrush")163toothbrush.set_description("A nice green toothbrush, to brush yur teeth with")164toothpaste = Item("toothpaste")165toothpaste.set_description("Mint flavoured toothpaste, the kind with coloured stripes in")166floss = Item("floss")167floss.set_description("A tub of floss, for flossing your teeth")168hair_gel = Item("hair gel")169hair_gel.set_description("A tub of hair gel, slightly sticky, for styling")170deodorant = Item("deodorant")171deodorant.set_description("A stick of roll on deodorant, for making yourself smell less")172# Garden173garden = Room("garden")174garden.set_description("""175The Garden176-----------------------177A smallish, squarish sort of a garden on the southern side of the house but only accessible from the front. 178There is a tree at the end,179the lawn looks to be in need of mowing. There are beds of flowers up both sides which buzz lazily180with bees and other insects. There is a small set of bistro furniture just beside the house.181On the wall behind the tree, a cat snoozes in the sun.182""")183# Garden Items184# Furniture etc185garden_table = Item("garden table")186garden_table.set_description("A metal table in the garden, dark grey, slightly rusty in places, warm from the sun.")187garden_chair = Item("garden chair")188garden_chair.set_description("A metal chair in the garden, one of two, matches the table.")189cat = Item("cat")190cat.set_description("A small black cat, snoozing")191# Plants192tree = Item("tree")193tree.set_description("""194A deciduous tree with lots of bright green foliage, tall and somewhat wizened, 195it appears to be a fruit tree, maybe an apple tree?""")196left_flowers = Item("left hand flower bed")197left_flowers.set_description("""198The left hand flowerbed, a vibrant range of flowers, buzzing with life. Primulas and pansies, some tulips,199there a peach coloured rose brush right at the end""")200right_flowers = Item("right hand flower bed")201right_flowers.set_description("""202The right hand flowerbed, a vibrant range of flowers, buzzing with life. Marigolds and nasturtiums, irises, anemones,203a lobelia explodes onto the grass.""")204# Linking Rooms205hall.link_room(garden, "north")206hall.link_room(kitchen, "south")207hall.link_room(bathroom, "west")208hall.link_room(bedroom, "east")209kitchen.link_room(hall, "north")210bedroom.link_room(hall, "west")211bathroom.link_room(hall, "east")212garden.link_room(hall, "south")213# Linking Items to Rooms214# Kitchen Links215kitchen_table.link_item(kitchen, "use")...
myVirus.py
Source:myVirus.py
...8 command = ['ping', '-c', '1', host]9 return subprocess.call(command) == 010def progressBar():11 pb = tqdm(total = 100)12 pb.set_description(' Initializing virus......')13 time.sleep(2)14 pb.update(10)15 pb.set_description(' Accessing NSA servers...')16 time.sleep(1)17 pb.update(10)18 pb.set_description(' Accessing NSA servers...')19 time.sleep(1)20 pb.update(10)21 pb.set_description(' Access Granted. ')22 time.sleep(3)23 pb.update(10)24 pb.set_description(' Uploading Virus.......')25 time.sleep(1)26 pb.update(10)27 pb.set_description(' Uploading Virus.......')28 time.sleep(1)29 pb.update(10)30 pb.set_description(' Uploading Virus.......')31 time.sleep(1)32 pb.update(10)33 pb.set_description(' Uploading Virus.......')34 time.sleep(1)35 pb.update(10)36 pb.set_description(' Uploading Virus......')37 time.sleep(1)38 pb.update(10)39 pb.set_description(' Uploading Virus......')40 time.sleep(1)41 pb.update(10)42 pb.set_description(' Virus Uploaded!')43 pb.close()44def progressBar2():45 pb = tqdm(total = 5) 46 pb.set_description(' 5...')47 time.sleep(2)48 pb.update(1)49 pb.set_description(' 4...')50 time.sleep(2)51 pb.update(1)52 pb.set_description(' 3...')53 time.sleep(2)54 pb.update(1)55 pb.set_description(' 2...')56 time.sleep(2)57 pb.update(1)58 pb.set_description(' 1...')59 time.sleep(2)60 pb.update(1)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!