mirea-projects/Second term/Discrete math/Задание_9.ipynb

1021 lines
276 KiB
Plaintext
Raw Normal View History

2024-09-23 23:22:33 +00:00
{
"cells": [
{
"cell_type": "markdown",
"id": "1ee388e8",
"metadata": {},
"source": [
"# Графы"
]
},
{
"cell_type": "markdown",
"id": "31fe6bcc",
"metadata": {},
"source": [
"## Определение графов. "
]
},
{
"cell_type": "markdown",
"id": "6cbbbe70",
"metadata": {},
"source": [
"\n",
" Неориентированным графом (или графом) называется пара $(V,E)$, где $V = \\{v_1, v_2,... \\}$ — множество вершин, $E = \\{e_1, e_2,... \\}$ — множество ребер, в котором каждый элемент $e_k$ является неупорядоченной парой $\\{v_i, v_j\\}$. Пара $(V,E)$, в которой множество $E$ состоит из упорядоченных пар $(v_i, v_j )$, называется ориентированным графом, а элементы из $E$ — дугами, или ориентированными ребрами. Вершины $v_i$ и $v_j$ , составляющие ребро или дугу, называются концевыми вершинами ребра или дуги, а про ребро и дугу говорят, что они соединяют свои концевые вершины.<br/> <br/>\n"
]
},
{
"cell_type": "markdown",
"id": "26e31d3b",
"metadata": {},
"source": [
"## Локальные характеристики"
]
},
{
"cell_type": "markdown",
"id": "ccdb2118",
"metadata": {},
"source": [
"Если $ e=\\{v_i, v_j\\} $ ребро графа, то вершина $ v_i $ и ребро е инцидентны. Вершина $ v_j $ и ребро е также инцидентны.<br/>\n",
"Вершины, инцидентные одному ребру, называются смежными.<br/>\n",
"Два ребра смежные, если инцидентны одной вершине.<br/>\n",
"Число вершин графа называется его порядком.<br/>\n",
"Число ребер графа, инцидентных данной вершине $vi$ , называется степенью $p(v_i)$ вершины $vi$ (другое обозначение $deg(v_i)$).<br/>\n",
"Если $ p(v_i)$ то $v_i$ изолированная вершина, если $p(v_i)=1$, то $v_i$ висячая вершина.<br/>\n",
"Если концевые вершины совпадают, то дугу $e=(v_i, v_j)$ называют петлей. <br/>\n",
"Очевидно, что для неориентированного графа $\\{v_i, v_j\\}=\\{v_j, v_i\\}$, а для ориентированного $(v_i, v_j)\\neq (v_j, v_i)$ .\n"
]
},
{
"cell_type": "markdown",
"id": "5eb6495a",
"metadata": {},
"source": [
"Нетрудно подсчитать число графов с фиксированным множеством вершин. Обозначим через $ N_g $ число неориентированных графов без петель с множеством вершин n.\n",
"<dt>Теорема (О количестве графов)</dt>\n",
" $$ N_g = 2^{\\frac{n(n-1)}{2}} $$\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "e8785f8f",
"metadata": {},
"source": [
"<dt>Теорема (Лемма о рукопожатиях)</dt> Сумма степеней всех вершин графа равна удвоенному числу ребер: \n",
" $$ \\sum p(v_i)=2|E| $$\n"
]
},
{
"cell_type": "markdown",
"id": "b4003ab7",
"metadata": {},
"source": [
"<dt>Следствие</dt> Сумма степеней вершин графа всегда четное число."
]
},
{
"cell_type": "markdown",
"id": "9d0d01ae",
"metadata": {},
"source": [
"<dt>Теорема</dt>\tВ любом графе число вершин нечетной степени четно.\n"
]
},
{
"cell_type": "markdown",
"id": "8efea77a",
"metadata": {},
"source": [
"## Способы представления графов"
]
},
{
"cell_type": "markdown",
"id": "a53868fa",
"metadata": {},
"source": [
"### Графическое представление графов. представление в виде списков смежности"
]
},
{
"cell_type": "markdown",
"id": "7e31a24f",
"metadata": {},
"source": [
"Обычно граф изображают на плоскости в виде множества точек, соответствующих вершинам, и множества линий, которые соединяют вершины и соответствуют ребрам. При изображении ориентированных графов линии снабжаются стрелками, указывающими ориентацию дуги, т. е. порядок вершин в паре."
]
},
{
"cell_type": "markdown",
"id": "eb9279ad",
"metadata": {},
"source": [
"Для работы с графами можно использовать библиотеку NetworkX, предназначенную для создания, манипуляции и изучения структуры, динамики и функционирования сложных сетевых структур. Внутреннее представление графов реализовано в виде списков смежности. <br/>\n",
"Основные возможности библиотеки:\n",
"<ol>\n",
" <li>Классы для работы с простыми, ориентированными и взвешенными графами</li>\n",
" <li>Узлом может быть практически что угодно: time-series, текст, изображение, XML</li>\n",
" <li>Сохранение / загрузка графов в/из наиболее распространённых форматов файлов хранения графов</li>\n",
" <li>Встроенные процедуры для создания графов базовых типов</li>\n",
" <li>Методы для обнаружения подграфов, клик и К-дольных графов (K-core) ( максимальный подграф в котором каждая вершина имеет по крайней мере уровень К )</li>\n",
" <li>Получение таких характеристик графа как степени вершин, высота графа, диаметр, радиус, длинны путей, центр, промежуточности, и т. д.</li>\n",
" <li>Визуализировать сети в виде 2D и 3D графиков</li>\n",
"</ol>\n"
]
},
{
"cell_type": "code",
"execution_count": 24,
"id": "98e1dde0",
"metadata": {},
"outputs": [],
"source": [
"#Если требуется установить библиотеку\n",
"# !pip install networkx"
]
},
{
"cell_type": "code",
"execution_count": 25,
"id": "b254ada3",
"metadata": {},
"outputs": [],
"source": [
"import networkx as nx \n",
"import matplotlib.pyplot as plt\n"
]
},
{
"cell_type": "code",
"execution_count": 26,
"id": "519b710b",
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAjIAAAFyCAYAAADvfDCoAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy80BEi2AAAACXBIWXMAAA9hAAAPYQGoP6dpAAAeTklEQVR4nO3df2ybd2Lf8c9D0qJNSqRNynLiRKzO0Y8kOl3v1gjyqdE5WnxeN+xUuENhr/YVW43csKsH1ECCZR4WX9zB6ABv3oAMuAK9LYPj1h3a+OZ17dXnVfE5daIz2suiUxZLmivTjRMpohKSIm3K5PPsj0SJfDZ/WHoo6Uu9X/8E4PM83+ebwJbeefh9nsdyHMcRAACAgTwrPQEAAIDFImQAAICxCBkAAGAsQgYAABiLkAEAAMYiZAAAgLEIGQAAYCxCBgAAGMtXyU62bevGjRtqaGiQZVnVnhMAAFjjHMdROp3W1q1b5fEUv+5SUcjcuHFDzc3Nrk0OAACgEtevX9fDDz9cdHtFIdPQ0PDZYKFQyJ2ZAQAAFJFKpdTc3PxZgxRTUcjMf50UCoUIGQAAsGzKLWmpKGQA1J5ML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AAIxFyAAAAGMRMgAAwFiEDAAAMBYhAwAAjEXIAAAAYxEyAADAWIQMAAAwlm+lJyBJmVxeE4mM5vK26nwetUSDCvpXxdQAAMAqtmK1MDaZ1qmhuAavTCk+k5WzYJslKRYJqL+jSft6Ymrb0rBS0wQAAKuY5TiOU26nVCqlcDisZDKpUCi0pBNen8nq8JlhXRyfltdjqWAXP/389r7
"text/plain": [
"<Figure size 700x1000 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAjIAAAFyCAYAAADvfDCoAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy80BEi2AAAACXBIWXMAAA9hAAAPYQGoP6dpAAAV1UlEQVR4nO3dfYyV5YH38d85w+sAM7yOFMtLAd/CY6ytrMaUUp91G9dsWNwaNWs31i3b7Rr/WDXbKEl9qU/q2qXiVrtpVBLZ1o2tLOyaxk2Nz1IXraJrK6GmKpQAviygA8wMDAzOnLN/sE6dFZhB3rz080nMcM59zXVfx7++uc81912p1+v1AAAUqHqiFwAA8EEJGQCgWEIGACiWkAEAiiVkAIBiCRkAoFhCBgAolpABAIo1aCCDarVa3nzzzYwaNSqVSuVYrwkA+Jir1+vp6OjIpEmTUq0e/LrLgELmzTffzOTJk4/a4gAABuK1117LJz/5yYMeH1DIjBo1qneypqamo7MyAICDaG9vz+TJk3sb5GAGFDLvfp3U1NQkZACA46a/LS0DCpljbXdXdza27s6+7lqGDKpm2rgRGTH0Q7E0AOBD7ITVwrqtHXlo9easfGVbNm/vzHsfwV1JMmVsYy44rSVXnjslp5x06MtKAMDHU6Ver9f7G9Te3p7m5ua0tbUd8VdLr23vzMIVa7Nq/dtpqFbSUzv46d89Pmfm+Hz7kjMzeWzjEZ0bACjDQNvjuN5H5uHnN+fCxU/mFxtak+SQEfPe47/Y0JoLFz+Zh5/ffMzXCACU47iF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>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"G = nx.Graph() # пустой неориентированный граф\n",
"G1 = nx.DiGraph() # пустой ориентированный граф\n",
"GG = nx.MultiGraph() # пустой мультиграф\n",
"GG1 = nx.MultiDiGraph() # пустой ориентированный мультиграф\n",
"\n",
"G.add_node(1) # добавляем одину вершину, получаем тоже пустой граф\n",
"G.add_nodes_from([3, 4, 5, 6, 7]) # добавляем еще шесть вершин сразу\n",
"\n",
"# В качестве обозначений вершин можем использовать ярлыки:\n",
"G1.add_nodes_from([\"node_1\", \"node_2\"]) # пустой ориентированный граф\n",
"\n",
"plt.figure(figsize =(7, 10))\n",
"plt.subplot(211)\n",
"nx.draw_networkx(G)\n",
"plt.show()\n",
"\n",
"plt.figure(figsize =(7, 10))\n",
"plt.subplot(212)\n",
"nx.draw_networkx(G1, with_labels = True)\n",
"plt.show()\n"
]
},
{
"cell_type": "code",
"execution_count": 27,
"id": "283ba2d2",
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAjIAAAFyCAYAAADvfDCoAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy80BEi2AAAACXBIWXMAAA9hAAAPYQGoP6dpAAA5o0lEQVR4nO3de0BVZb7/8c/ae8NWEJBLaCaoCZoxTlcFzEukWdboZE1qIWX3fmZJM9U01tG0jlOT08Vj02062aBF5tFqOpN5iczGUE9jJeS1UjRNEuQiKLAvvz+MplJgA3uz9uX9+qfaa61nfUOUj8/6rucx3G63WwAAAAHIYnYBAAAAbUWQAQAAAYsgAwAAAhZBBgAABCyCDAAACFgEGQAAELAIMgAAIGARZAAAQMCyeXKSy+XS/v37FRUVJcMwfF0TAAAIcW63W9XV1erRo4cslqbnXTwKMvv371dSUpLXigMAAPDE3r171bNnzyaPexRkoqKifhgsOjraO5UBAAA0oaqqSklJST9kkKZ4FGQaHydFR0cT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50kyzhnZu9R3J8BI2+AAB4iJ+YrZTVP1F5G/Y0+Qp25IBhOvL5KlVv/odcR6tlCe+s8O4pir3whib3WmpktRjK6pfoi7IBAAhKBJlWyk5P1sKPdzd5PPLMEYo8c0Sbxna63JqcwcaRAAB4ih6ZVkrtFqVhKQkere7bGlaLoWEpCUpJjPLquAAABDOCTBvMHT9QNi8HGZvF0NzxA706JgAAwY4g0wZJcRGaPc672wjMGZempLgIr44JAECwI8i00aRBybpndD9JanG13pbcO7q/Jg6iNwYAgNYiyLTDsLhaVa76i6xytbpnxmpIdptFj105UHdkpfioQgAAghtBpo1qamo0ceJE9XJ8o5XTh2nI6fGS1GKgsX5/ON5ZptV3j2AmBgCAdiDItNGdd96pvXv36vXXX1fKqbHKuyldq3KHKye9l3rFR5ywArAhqVd8hHIyeuuKsC3aMv822eoqzSgdAICgYbg9aPCoqqpSTEyMKisrFR0d3RF1+bVXX31V2dnZevnllzVlypSTnlNT59DushrVO1wKt1nUOz7yhxV7Kyoq1KdPH1133XV6+umnO7ByAAACg6fZgyDTSl9++aXOOeccjR07VosWLZJhtO017EceeUSPPPKIvvzyS5122mlerhIAgMDmafbg0VIr1NfXa9KkSUpMTNSzzz7b5hAjSXfddZciIyP1xz/+0YsVAgAQWggyrfDAAw/os88+U35+frtnpqKjo3XvvffqxRdfVElJiZcqBAAgtBBkPPTuu+9q3rx5evTRR3X++ed7Zcxp06YpOjpac+fO9cp4AACEGoKMBw4cOKDrr79eY8aMUW5urtfG7dKli+677z699NJL2r17t9fGBQAgVBBkWuByuZSTkyOr1aqFCxfKYvHul2zq1KmKi4vTI4884tVxAQAIBQSZFjz22GN6//33tWjRIiUmJnp9/MjISN1///1auHChvvzyS6+PDwBAMCPINGP9+vX6j//4D/3hD3/QyJEjfXaf22+/Xaeccooefvhhn90DAIBgRJBpQkVFha699lqlp6froYce8um9OnfurBkzZigvL087duzw6b0AAAgmBJmTcLvduvnmm1VZWalXX31VYWFhPr/nLbfcolNPPVVz5szx+b0A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XyfDsMhVf0xut6vFcZ0ut9btOqRdpdXeLrldGmdlCgoKVFBQYHY5AAD4jYAMMos3lMhqaXrhumO7P5Vhj5DjSJm+eeE27X3iN9r7xASVvfeM3I76Zse2WgwtKizxdsntNnbsWJ133nmaNWuWPJhEAwAgJARkkCnYXtrsG0oN5fsll1Pf/c/D6tznXJ0yfoa6/PJ
"text/plain": [
"<Figure size 700x1000 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# добавляем в графы ребра и дуги\n",
"G.add_edges_from([(1, 2), (1, 3), (1, 4), (2, 4), (2, 6), (3, 6), (4,7), (5, 7)]) # для неориентированного графа\n",
"G.add_edge(8,9) # добавление ребра с новыми вершинами, добавит их тоже\n",
"\n",
"plt.figure(figsize =(7, 10))\n",
"plt.subplot(211)\n",
"nx.draw_networkx(G)\n",
"plt.show()\n"
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "d273c0ff",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"NodeView((1, 3, 4, 5, 6, 7, 2, 8, 9))"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"G.nodes()"
]
},
{
"cell_type": "code",
"execution_count": 29,
"id": "98549f52",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"9"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Количество вершин в графе G\n",
"G.number_of_nodes()\n",
"# G.order\n",
"# len(G)"
]
},
{
"cell_type": "code",
"execution_count": 30,
"id": "b8d574e8",
"metadata": {},
"outputs": [],
"source": [
"G.edges()\n",
"nx.write_edgelist(G, \"Graf.txt\")"
]
},
{
"cell_type": "code",
"execution_count": 31,
"id": "ea2178eb",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"9"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# количество ребер\n",
"G.number_of_edges()"
]
},
{
"cell_type": "code",
"execution_count": 46,
"id": "2925c211",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"DiGraph with 9 nodes and 9 edges\n"
]
}
],
"source": [
"# создание графа из файла\n",
"G2 = nx.read_edgelist(\"Graf.txt\", nodetype = int, create_using = nx.DiGraph()) #считываем список ребер из файла, по умолчанию неориентированный\n",
"nx.is_directed(G2)"
]
},
{
"cell_type": "code",
"execution_count": 33,
"id": "4316a607",
"metadata": {
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[2, 3, 4]\n",
"[5, 6, 7, 8, 9]\n"
]
}
],
"source": [
"# список соседей вершины графа\n",
"#list(G.neighbors(1))\n",
"print(list(nx.all_neighbors(G, 1))) # список соседних вершин\n",
"print(list(nx.non_neighbors(G, 1))) # список остальных вершин"
]
},
{
"cell_type": "code",
"execution_count": 34,
"id": "be070e29",
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAjIAAAFyCAYAAADvfDCoAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy80BEi2AAAACXBIWXMAAA9hAAAPYQGoP6dpAAAz2klEQVR4nO3dcVSUh4Hv/d8zSAjGURKMIVSNmBSaAaHAoiuaOnC7EboelG1J0NYq0bKGty/GspcNnhVjdDHkRmnYbmlsqIQ2hZrcSFkTje0VeRNxgxdYBIZiUk2UKkkxQSAYggzvH2ndkMSICjwz8P2c4/HAjDO/4R+/52HmeYyBgYEBAQAAuCGL2QMAAACuFyEDAADcFiEDAADcFiEDAADcFiEDAADcFiEDAADcFiEDAADcFiEDAADc1oSh3MnpdOrs2bOyWq0yDGOkNwEAgHFuYGBAXV1d8vf3l8Vy5eMuQwqZs2fPasaMGcM2DgAAYCjOnDmj6dOnX/H2IYWM1Wq9/GCTJ08enmUAAABX0NnZqRkzZlxukCsZUsj89ddJkydPJmQAAMCoudpbWnizLwAAcFuEDA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FRYWKjc3V/X19Xruuee0du1a/fznP5ckpaWladq0aXrqqad0h/dc3XxXqPp7LujCG/9b3ndH6fbvZMswDFklfVBZrM6jewY9X2d1mS51tOnOlKfledtXJEnW8Hh5TLpNnW+8pMlzEzVh8u2SpNPne/Rh76VrupxBbm6uPDw89J3vfOcGfzIAAGCoTHuz77p16wZ9fd999+n8+fPq7OzUK6+8Ikn60Y9+NOg+GRkZkqSLfzwmSfro7f+S+i/JGrlEhmFcvt/kqKWfe76eP7wurxnBstw8Sf09Fy7/uXnW16UBpz4603j5vgOS3j7/4ZBfy69//WsVFhYqIyNDX/0q56IBAGC0mHZEZubMmYO+vvXWWyVJH3zwgd555x1ZLBbdc889g+7j5+cn6+QpunThPUm6/PeEvxxh+SuPiVNkuXnSoO9d+uCc+v78tlrzv/uFe5wfXhj09ceXnF94v8967bXXtGbNGi1evFj/+q//OqR/AwAAhodpIePh4fGF3//0pZ8+fZTlv793fc83MODUzbPCNflvv/2Ft3ve6j/o65smXP1gVX19vRISEhQSEqIXX3xREya45YfAAABwWy75P+9dd90lp9OpN998U/fee+/l77/77rvqvHBBk4OmSZImTPnk70vv/0mePn6X79ffc0HOj7oHPabnrXdqoO+ivGd9/arPb0ia5XvLl97nj3/8o+Li4jRt2jS98sormjRp0pfeHwAADD+XPCHet771LUnSj3/840Hf37lzpyRp1tcXStIn72+xTFBXzb5BR3I6j/32c4858WsL1funP+jiyZrP3eb8qFsDzv7LX8/0nfilb/Rta2vT/fffL4vFoldffVW33377kF8bAAAYPi55RCYsLEyrVq3Srl271NHRoUWLFqm6ulrPPfecli1bprC/X6xfvvGONHGKJs9LVOfRF/TnF7fIe/bf6ON3T+riyf8ri/fgS35PnvcPuvjmG3rvxcc1ac7/0E1+92jg44/08Z/fUU/LEX3l4UJ5TJwiD4uhmMBpX7ovLi5OJ0+eVGZmpl5//XW9/vrrl2+744479Hd/93cj8nMBAACDuWTISNKzzz6r2bNnq6ioSHv37pWfn5+ysrK0efNmne74WEVH35Yk+X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Kzc1VdXW1JGnevHn653/+Z128eNHkZQAAjD2EzAiJiIhQdXW1tm7dqqefflqhoaE6fPiw2bMAABhTCJkR5OnpqaysLNXX1+vOO+9UTEyMUlNT1dHRYfY0AADGBEJmFAQFBenw4cM
"text/plain": [
"<Figure size 700x1000 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"G1.add_edges_from([(\"node_1\", \"node_2\")]) # для ориентированного графа\n",
"\n",
"plt.figure(figsize =(7, 10))\n",
"plt.subplot(212)\n",
"nx.draw_networkx(G1)\n",
"plt.show()\n"
]
},
{
"cell_type": "code",
"execution_count": 35,
"id": "04767bda",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3\n"
]
},
{
"data": {
"text/plain": [
"DegreeView({1: 3, 3: 2, 4: 3, 5: 1, 6: 2, 7: 2, 2: 3, 8: 1, 9: 1})"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# степени вершин\n",
"print(G.degree(1))\n",
"G.degree()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bd241395",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"id": "de4d11f9",
"metadata": {},
"source": [
"### Представление графов виде матриц"
]
},
{
"cell_type": "markdown",
"id": "ad160898",
"metadata": {},
"source": [
"#### Матрица смежности"
]
},
{
"cell_type": "markdown",
"id": "c35cad09",
"metadata": {},
"source": [
"Матрицей смежности $A=A(a_{ij})$ графа G называется матрица порядка n, определенная следующим образом:\n",
"$$a_{ij}=\\begin{cases} 1, &если& e_{ij} \\in E \\\\ 0, &если& e_{ij} \\notin E \\end{cases} $$\n",
" \n",
"Матрица смежности для неориентированного графа будет симметрична относительно главной диагонали. Матрица смежности для ориентированного графа в общем случае не симметрична относительно главной диагонали."
]
},
{
"cell_type": "code",
"execution_count": 36,
"id": "b9ef4b36",
"metadata": {
"scrolled": true
},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAA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rU1NSkd955p6tLAYCIEWSAr5mzqlS+II+SEnOnaOgtv1PKxB8rcczF6n/BNJ0y/ZcyA341bHm59QENQ454p4zc/9SgQYNiWHnHnHXWWUpOTqZPBoClEGSA45RXNWpjRU3Qnpg+w86UYY87YVtcylDFp2WqpaYy6LgBU9pYUaOK6sao1htNdrtdF154IX0yACyFIAMcZ8VWd5tXizZNU37vQdkSQi/fYbcZWr7l5LeYupOCggJt2rRJLS0tXV0KAESEIAMcp2RXdZvfUPLseFP+xlq5zsgPeZw/YKqkrLoj5cVcYWGhvF6v3nvvva4uBQAiQpABvnKoySd3nbdN57TUVqru77+Vc+gZco2+KOzx7lqvPE2+9pYYc9/61rfkcrnokwFgGQQZ4Ct7az1qy70Y/6EvVP3Hh2RzupR2xf0ybPaw55iS9tR62l1jrMXFxWn8+PH0yQCwDIIM8JVmXyDiYwNHPKp6aa4CRzxKv+YhORJTY3KdrlBQUKC33npLfr+/q0sBgLAIMsBX4h2R/XUwfc2qfnmefF/sU/rVDyg+LTMm1+kqhYWFamho0L/+9a+uLgUAwureP1GBTjQ81aVw7yuZAb8+f+2Xatr/kQZecZ+cQ89s0zWMr67TneXm5srpdNInA8ASCDLAV1xOhzJDrFYtSV/837M6XLFVfU87V/7Dh3Roe8kJ/wsnMzVBLmf3XhmkT58+GjduHH0yACyhe/9EBTpZ0ch0Ldu6N+gr2M1VuyVJhyve0eGKk6fy7/fNoqBj222GikakR6fQGCs
"text/plain": [
"<Figure size 700x1000 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[0 1 1 0 0 0 1 0 0]\n",
" [1 0 0 0 1 0 0 0 0]\n",
" [1 0 0 0 0 1 1 0 0]\n",
" [0 0 0 0 0 1 0 0 0]\n",
" [0 1 0 0 0 0 1 0 0]\n",
" [0 0 1 1 0 0 0 0 0]\n",
" [1 0 1 0 1 0 0 0 0]\n",
" [0 0 0 0 0 0 0 0 1]\n",
" [0 0 0 0 0 0 0 1 0]]\n"
]
}
],
"source": [
"plt.figure(figsize =(7, 10))\n",
"plt.subplot(212)\n",
"nx.draw_networkx(G)\n",
"plt.show()\n",
"\n",
"a= nx.adjacency_matrix(G) # список вершин, которые соединены попарно, и веса связывающих их ребер.\n",
"A=a.todense() # Формируем матрицу смежности\n",
"print(A)"
]
},
{
"cell_type": "code",
"execution_count": 37,
"id": "22c6a448",
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAjIAAAFyCAYAAADvfDCoAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy80BEi2AAAACXBIWXMAAA9hAAAPYQGoP6dpAABPaElEQVR4nO3deVyNaR8G8OucUikqZbLWGFKUkiXZyTqWsRuGLJN9GcYSXjL2GMMYxmAYZM8Y69hFkiihTaEUFWZQkZROnXOe9w9Tk9GqU2fp+n4+83nHebbf8U7nXN33/XsekSAIAoiIiIjUkFjZBRARERF9LAYZIiIiUlsMMkRERKS2GGSIiIhIbTHIEBERkdpikCEiIiK1xSBDREREaotBhoiIiNSWdlF2ksvlePr0KSpXrgyRSFTaNREREVE5JwgCUlNTUbNmTYjF+Y+7FCnIPH36FObm5gorjoiIiKgoEhISULt27Xy3FynIVK5cOedkhoaGiqmMiIiIKB+vX7+Gubl5TgbJT5GCTPZ0kqGhIYMMERERlZnClrRwsS8RERGpLQYZIiIiUlsMMkRERKS2GGSIiIhIbTHIEBERkdpikCEiIiK1xSBDREREaotBhoiIiNQWgwwRERGpLQYZIiIiUlsMMkRERKS2GGSIiIhIbTHIEBERkdpikCEiIiK1pa3sAoiIiBQhTSLFo6Q0ZErl0NEWo46pAQx0+TWn6fj/MBERqa3oZ6nYFxgPn/vPEZ+cDiHXNhEACxN9OFubYbiTBepXq6ysMqkUiQRBEArb6fXr1zAyMkJKSgoMDQ3Loi4iIqJ8JSSnY/7RcPg9SISWWASZP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DWFhYuQkxAGBlZYUVK1bg0aNHuHDhApo3b45ly5bBwsIC3bt3x/79+5Ge/u+DMQ8ePIiePXti3LhxkMvzvwmgV1A8uqzzxbXYJAAotIsre/u12CR0WecLr6B4Bbw75WKQISKiUiOVSrFq1So4ODggKSkJV65cwfr161GpUiVll6YUWlpa6NKlC/bu3Yu///4b27Ztw9u3bzF8+HDUqFED48aNg7+/P7Zv3w6RSARPT0/MmjULeU2ebPSJxrwj4ZBI5cVqQwfeBRqJVI55R8Kx0SdaUW9PKTi1REREpSIsLAyurq4IDg7G7NmzsXjxYlSsWFHZZamkmJgY7N69G7t27UJcXNwH25ctWwZ3d/ecP3sFxZfpXY6VgVNLRESkFJmZmViyZAmaN2+OjIwMBAQE4Pvvv2eIKUC9evWwZMkSxMbGYsyYMR8sBF64cCHWrl0L4N2amEUnIhR6/e9ORCAhOb3wHVWQevViERGRSrt16xa+/vpr3L17F/Pnz8f8+fOhq6ur7LLUhkgkwqVLl/KcSpo9ezaqV6+OsxmWkBZzKqkwUrmA+UfDsWeMk0LPWxY4IkNERCWWkZGB//3vf3BycoK2tjaCgoKwZMkShphievnyJR4+fAgAqFChAszNzdGqVSv07t0bXbt2hVl9e/g9SMx3TUxGXBjiVvVG+v1rH2xLi7iMuFW9IXly94NtMrkAvweJePA8VbFvqAxwRIaIiErk2rVrcHV1xcOHD7F06VK4ubmhQoUKyi5LLZmYmODJkyfQ0dGBqanpB1NMi09EFNhirWthBy3DT5AWeRn61q3f25YWeRnaxjWgW6thnsdqiUXYGxCPxX1sFfNmyghHZIiI6KOkp6dj5syZaNu2LYyNjREcHIz58+czxJRQzZo1UbVq1TxvmOdz/3mBHUoikQgGth2R/iAI8oy0nNdl6Sl4+zAYBrYd8z1WJhfgE6V+T/NmkCEiomK7fPky7O3tsXnzZqxZswb+/v6wsbFRdlka7Y1EivgiLMit1KgTIMtC2n3/nNfS7l4B5DI
"text/plain": [
"<Figure size 700x1000 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[0 1 1 1 0 0 0]\n",
" [0 0 0 1 1 0 0]\n",
" [0 0 0 0 1 0 0]\n",
" [0 0 0 0 0 1 0]\n",
" [0 0 0 0 0 0 0]\n",
" [0 0 0 0 0 0 0]\n",
" [0 0 0 0 0 1 0]]\n"
]
}
],
"source": [
"G2 = nx.DiGraph()\n",
"G2.add_edges_from([('q', 'w'), ('q', 'e'), ('q', 'r'), ('w', 'r'), ('w', 'y'), ('e', 'y'), ('r','u'), ('t', 'u')])\n",
"\n",
"plt.figure(figsize =(7, 10))\n",
"plt.subplot(212)\n",
"nx.draw_networkx(G2)\n",
"plt.show()\n",
"\n",
"a= nx.adjacency_matrix(G2) # список вершин, которые соединены попарно.\n",
"A=a.todense() # Формируем матрицу смежности\n",
"print(A)"
]
},
{
"cell_type": "markdown",
"id": "94a7923d",
"metadata": {},
"source": [
"<dt>Теорема</dt>\tГрафы изоморфны тогда и только тогда, когда их матрицы смежности получаются друг из друга одновременными перестановками строк и столбцов (т.е. одновременно с перестановкой $i$-й и $j$-й строк переставляются $i$-й и $j$-й столбцы)."
]
},
{
"cell_type": "markdown",
"id": "904e294c",
"metadata": {},
"source": [
"#### Матрица инцидености"
]
},
{
"cell_type": "markdown",
"id": "685333ab",
"metadata": {},
"source": [
"Матрицей инцидентности $B=(b_{ij})$ неориентированного графа G называется матрица размера $ |V|\\times|E|$ , в которой столбцы матрицы соответствуют ребрам, строки — вершинам. Ненулевое значение в ячейке матрицы указывает связь между вершиной и ребром определяемую следующим образом: \n",
"$$b_{ij}=\\begin{cases} 1, &если& e_{j} &инцидентна\\space вершине& a_i \\\\ 0, &иначе& \\end{cases} $$ \n",
"<br/>\n",
"В случае наличия ориентированных дуг, начало и конец обозначаются противоположныти знаками\n",
"$$b_{ij}=\\begin{cases} 1, &если& e_{j} &исходит\\space из\\space вершины& a_i \\\\ -1, &если& e_{j} &заходит\\space в\\space вершину& a_i &и\\space не\\space является\\space петлей& \\\\0, &иначе& \\end{cases} $$\n",
" \n"
]
},
{
"cell_type": "code",
"execution_count": 38,
"id": "5d0d0824",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[1. 1. 1. 0. 0. 0. 0. 0. 0.]\n",
" [0. 1. 0. 1. 0. 0. 0. 0. 0.]\n",
" [0. 0. 1. 0. 1. 1. 0. 0. 0.]\n",
" [0. 0. 0. 0. 0. 0. 1. 0. 0.]\n",
" [0. 0. 0. 1. 0. 0. 0. 1. 0.]\n",
" [0. 0. 0. 0. 0. 1. 1. 0. 0.]\n",
" [1. 0. 0. 0. 1. 0. 0. 1. 0.]\n",
" [0. 0. 0. 0. 0. 0. 0. 0. 1.]\n",
" [0. 0. 0. 0. 0. 0. 0. 0. 1.]]\n"
]
}
],
"source": [
"a= nx.incidence_matrix(G) # список вершин, которые соединены попарно.\n",
"A=a.todense() # Формируем матрицу инцидентности\n",
"print(A)"
]
},
{
"cell_type": "code",
"execution_count": 39,
"id": "afa251b7",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[ 1. 1. 1. 0. 0. 0. 0. 0.]\n",
" [-1. 0. 0. 1. 1. 0. 0. 0.]\n",
" [ 0. -1. 0. 0. 0. 1. 0. 0.]\n",
" [ 0. 0. -1. -1. 0. 0. 1. 0.]\n",
" [ 0. 0. 0. 0. -1. -1. 0. 0.]\n",
" [ 0. 0. 0. 0. 0. 0. -1. -1.]\n",
" [ 0. 0. 0. 0. 0. 0. 0. 1.]]\n"
]
}
],
"source": [
"b= -nx.incidence_matrix(G2, oriented=True) # список вершин, которые соединены попарно.\n",
"B=b.todense() # Формируем матрицу инцидентности\n",
"print(B)"
]
},
{
"cell_type": "markdown",
"id": "d7a85452",
"metadata": {},
"source": [
"<dt>Теорема</dt>\tГрафы и изоморфны тогда и только тогда, когда их матрицы инцидентности получаются друг из друга некоторыми перестановками строк и столбцов."
]
},
{
"cell_type": "markdown",
"id": "d838ad99",
"metadata": {},
"source": [
"## Операции над графами"
]
},
{
"cell_type": "markdown",
"id": "dc315442",
"metadata": {},
"source": [
"В результате операции добавления к графу $G=\\langle V,E \\rangle$ вершины $a$ a образуется граф $G1=\\langle V\\cup \\{a\\},E \\rangle$ .<br/> В результате операции добавления дуги $e$ к графу G образуется графа $G2=\\langle V,E\\cup \\{e\\} \\rangle$.<br/>\n",
"Под операцией удаления дуги $e$ из графа $G$ понимается операция, заключающаяся в удалении пары $(a_i, a_j)$ из множества дуг $E$. <br/>Операция удаления вершины a из графа $G$ заключается в удалении вершины a вместе с инцидентными ей дугами.<br/> При замыкании двух вершин, эти вершины удаляются из графа и заменяются одной новой, при этом ребра, инцидентные исходным вершинам, теперь будут инцидентны новой вершине. В случае, когда отождествляемые вершины соединены дугой, операцию отождествления называют стягиванием дуги.\n"
]
},
{
"cell_type": "code",
"execution_count": 40,
"id": "85892ea0",
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAgMAAAC8CAYAAADl2K3eAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy80BEi2AAAACXBIWXMAAA9hAAAPYQGoP6dpAAA3GElEQVR4nO3deVhUdfvH8ffMsG8uIAYKiqIii2hpKiiGWy65m1hamrb4mPuWS5pL+Wgu6U8rK3O3tMUtMzVXUMzcJXABd8VcQNllm/n9QfBILKIMnIG5X9fVdcHMmTn3MZ3zmXO+3++t0ul0OoQQQghhtNRKFyCEEEIIZUkYEEIIIYychAEhhBDCyEkYEEIIIYychAEhhBDCyEkYEEIIIYychAEhhBDCyEkYEEIIIYycSVE20mq1REdHY2tri0qlKumahBBCCKEHOp2OhIQEnJ2dUasL/v5fpDAQHR2Ni4uL3ooTQgghROm5ceMG1atXL/D5IoUBW1vbnDezs7PTT2VCCCGEKFHx8fG4uLjknMcLUqQwkH1rwM7OTsKAEEIIUcY86Ra/DCAUQgghj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ZmZmbONMh/B4XExEQALCwsclpGPx4SateuLdMghRDiGUgY0JPw8HA6dOiAWq1m586d1K9fX+mSyhWdTsfNmzfzjEkIDw/PWQPC1NQ0Zxrk47cb6tati4WFhcJHIIQQhkvCgB7dvHmTDh06cPv2bbZv307z5s2VLqnc0+l03L17N98ZDn///TeQ1W66du3aecYkeHh4YGNjo/ARCCGE8iQM6NmDBw/o1q0bx48fZ8OGDXTt2lXpkox
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import numpy as np\n",
"A=np.array([[1, 0, 1, 0], \n",
" [1, 1, 0, 0], \n",
" [0, 1, 1, 0], \n",
" [0, 1, 1, 1]])\n",
"G = nx.DiGraph(A)\n",
"plt.subplot(212)\n",
"nx.draw_networkx(G)"
]
},
{
"cell_type": "code",
"execution_count": 41,
"id": "059ef702",
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAgMAAAC8CAYAAADl2K3eAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy80BEi2AAAACXBIWXMAAA9hAAAPYQGoP6dpAAAvYElEQVR4nO3deVxU9d4H8M8s7CDImgiICqIi2oJprmG4lAKi3twQ10RNM69mqd205fE++ZjWvZmDoJjbdUkNVNxCUnILzQbEBVwhEZBFGUAZZuY8fxjckB0ZBpjP+/XiVc7ZvkfL85nf+Z3vEQmCIICIiIj0lljXBRAREZFuMQwQERHpOYYBIiIiPccwQEREpOcYBoiIiPQcwwAREZGeYxggIiLScwwDREREek5am5U0Gg3S09NhYWEBkUik7ZqIiIioAQiCAIVCAUdHR4jFVX//r1UYSE9Ph7Ozc4MVR0RERI0nLS0NTk5OVS6vVRiwsLAo21mrVq0apjIiIiLSqvz8fDg7O5ddx6tSqzBQemugVatWDANERETNTE23+DmBkIiISM8xDBAREek5hgEiIqJnzJ8/H1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TPRuXNnXZenFXK5HCYmJnB3d9d1KVrFMEBERNVKS0tDeHg4wsPDkZ6ejt69e2Pz5s14++23YWJiouvytEoul6Nbt26QSCS6LkWrGAaIiKgCjUaDY8eOQSaT4cCBAzA1NUVQUBBCQkLw4osv6rq8RiOXy1tkX4FnMQwQEVGZrKwsbNq0CRs2bMDt27fRo0cPrFu3DhM
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Удаление ребра\n",
"G.remove_edge(3,1) \n",
"plt.subplot(212)\n",
"nx.draw_networkx(G)"
]
},
{
"cell_type": "code",
"execution_count": 42,
"id": "c17ab9ba",
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAgMAAAC8CAYAAADl2K3eAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy80BEi2AAAACXBIWXMAAA9hAAAPYQGoP6dpAAAZg0lEQVR4nO3de3RU9b338c/eM5ncE3IhXJMKhwBPQjhSy0Ko3CRSLQ9UXAo8R+ARQTiPUo9Q6QJpq9Jqe7pcj7bFCxctF6megwgEijwV9QA92ohcFjhIISAkEAz3ZHIhyczs5w9MSkgmCckEJuz3a60szf7t24+VZH/mt7/7tw3LsiwBAADbMm/2CQAAgJuLMAAAgM0RBgAAsDnCAAAANkcYAADA5ggDAADYHGEAAACbIwwAAGBzzuas5Pf7VVhYqNjYWBmG0dbnBAAAgsCyLHk8HnXt2lWmGfjzf7PCQGFhoVJTU4N2cgAA4MYpKChQ9+7dA7Y3KwzExsbW7iwuLi44ZwYAANpUSUmJUlNTa6/jgTQrDNTcGoiLiyMMAADQzjR1i58CQgAAbI4wAACAzREGAAC4xty5czVjxgwdO3bsZp/KDUEYAADgGhs2bNCbb76p9PR0Pfroo7d8KCAMAAAQgN/v16pVq5Senq4pU6bo4MGD8vv9unTpksrLy+X1em/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Z0TAADqae71O+TCgN/v10svvaSf//znCgsL07Rp0zR79mz16dOndp3Bgwfri6++Vuexc+To3k8Ow5CvkW44TEM+v6WhvZL14vgspSZGSZIuXryo1at
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Удаление вершины\n",
"G.remove_node(2) \n",
"plt.subplot(212)\n",
"nx.draw_networkx(G)\n"
]
},
{
"cell_type": "code",
"execution_count": 43,
"id": "2d012b55",
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAgMAAAC8CAYAAADl2K3eAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy80BEi2AAAACXBIWXMAAA9hAAAPYQGoP6dpAAAunklEQVR4nO3deVxU5f4H8M8s7JssIrIMMOOamuaGmsrF1NLcl5+5/bJu1k+7aam3zNxL+6V1tdKuedNSc/lRF6+amlFSggsgZOGSIfsmyDoMwzZz5veHMUUCojKcGebzfr18JXOeOfM9Bjzf8zzP+T4Sg8FgABEREVktqdgBEBERkbiYDBAREVk5JgNERERWjskAERGRlWMyQEREZOWYDBAREVk5JgNERERWjskAERGRlZM3p5EgCMjNzYWLiwskEompYyIiIqIWYDAYUF5eDl9fX0iljd//NysZyM3NRUBAQIsFR0RERK0nKysL/v7+jR5vVjLg4uJiPJmrq2vLREZEREQmpVarERAQYOzHG9OsZKBuasDV1ZXJABERWa2Kah3SiypQoxNgK5ciyNMJTnbN6kpFdbcpfvO/AiIiIhEl55djf2wmoq4XILNYiz/u7icBoPBwRFhXb8wOUaBzh6bvwM2VpDm7FqrVari5uaGsrIwjA0REZBWyirVYcTgJ0TcKIZNKoBca7y7rjg/r5IWNk3shwMOxFSNtXHP7bz5aSERE9CeH4jMxcssPOJdaBABNJgJ/PH4utQgjt/yAQ/GZJo+xJXGagIiI6A+2RSXj3W9+va/36gUD9II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FCY
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Дополнение графа\n",
"H = nx.complement(G)\n",
"plt.subplot(212)\n",
"nx.draw_networkx(H)"
]
},
{
"cell_type": "markdown",
"id": "fe9a389c",
"metadata": {},
"source": [
"Очевидно, имеем следующие утверждения:<br/>\n",
"У всякого графа имеется пустой подграф.<br/>\n",
"Всякий граф является подграфом полного графа.<br/>\n",
"Если граф G является подграфом графа G1, а граф G2 подграфом графа G1, то G2 подграф графа G, (то есть отношение «быть\n",
"подграфом» транзитивно).\n"
]
},
{
"cell_type": "markdown",
"id": "7a893bea",
"metadata": {},
"source": [
"## Задание"
]
},
{
"cell_type": "markdown",
"id": "f177290d",
"metadata": {},
"source": [
"**Задание 1.** Сгенерировать несколько ориентированных и несколько неориентированных графов различными способами (включая считывание из файла). Выполнить с ними все известные операции. Получить для них матрицы смежности и инцидентности. Вывести степени вершин, списки ребер и вершин."
]
},
{
"cell_type": "code",
"execution_count": 59,
"id": "424ba7bc",
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAApQAAAIKCAYAAACdo98PAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy80BEi2AAAACXBIWXMAAA9hAAAPYQGoP6dpAABaA0lEQVR4nO3dd3RU9drF8T2TkCCEGnrvpBB6R6SoqKgIqCggil2aIAgqohSR3gkkEJAOglQRRIpBqqFKCb2GIoSEkkogmfP+4SWvMfSUk8x8P2ux1s3MmTN7RuBunt8pFsMwDAEAAACPyWp2AAAAAGRuFEoAAACkCIUSAAAAKUKhBAAAQIpQKAEAAJAiFEoAAACkCIUSAAAAKUKhBAAAQIpQKAEAAJAiFEoAsHO+vr66fv164s/jxo1TdHS0eYEA2B0KJZBBBAcH66233lLRokXl6uqqIkWKqH379goODjY7GjK5lStXasCAATp37pzm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R0qVLk3w/91qWL1++fLLvJ3v27Hfd1sfHJ9m2Tk5Od922du3aqlmzpiTpxRdf1L59+7RmzZq7bntHTEyMBg4cqM6dOyf73Knp+PHjyR47duxY4n+Ta9euacOGDRo4cKC+/fbbe74uX758ypIliy5evPjA97xw4YIkqUiRIilIDiClWPIGTNa7d2898cQT+vjjj5MVqKtXr+qTTz5RtmzZ1Lt372SvnTRpUpKfJ06cKEl64YUXkjy+fft
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAApQAAAIKCAYAAACdo98PAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjkuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy80BEi2AAAACXBIWXMAAA9hAAAPYQGoP6dpAABExElEQVR4nO3de3icdZ3//9c9k/P51KRNmsncN20KlIInFixW6IqgwhbxAPjTLxRdQFdgZb+w1O5KoSywaFngAl2B716IwAoWRVEEK7uFRUBEROmyStulSdr0kOZ8PszM/fujTkyaSTLJzOT+TPJ8XFeuq3O6855pIK9+7vt+3Zbruq4AAACAWfJ5PQAAAADSG4ESAAAACSFQAgAAICEESgAAACSEQAkAAICEECgBAACQEAIlAAAAEkKgBAAAQEIIlAAAAEgIgRIAIEm69dZbFYlEJEmRSES33XabxxMBSBcESiBFvvOd78iyLP3mN7+J+fgZZ5yhE044YY6nAib30EMPacuWLdq3b5/uuOMOPfTQQ3G97vnnn5dlWZN+/fKXv0zx5OOdcMIJOuOMM+b0ewILXYbXAwAAzLB582ZdfPHFuv7665Wdna1HHnlkRq+/+uqrdfLJJ0+4f8WKFckaEYChCJQAAEnShRdeqLVr12r37t1avny5Fi1aNKPXr1mzRp/61KdSNB0Ak7HLGzDMI488ove+973Kzc1VWVmZLrroIu3du3fC87Zu3Tr6vIqKCn3uc59Tc3PzuOesX79eBQUFeuedd3T22WcrPz9f1dXV2rx5s1zXHX1eQ0ODLMvSd77znXGv//KXvyzLsrR+/fpx93d2duorX/mKamtrlZ2drWXLlun2228fPf5u7Da3bNkyYfaxuySn211qWZZuvPFGSdKNN94oy7LGbau3t1eLFy+WZVl6/vnnR++PHlLw+uuva/Xq1crNzZVt2/r2t789YZ6WlhZ94QtfUFVVlXJycnTSSSdN2N0bfT/Rr8zMTAWDQV133XUaHh4efV57e7uuvfZarVq1SgUFBSoqKtJHP/pR/f73vx+3vej7fuKJJybMU1BQMO4zn+zwidbW1nGfz9jPqLW1dcJ2o4LBYMztNzQ0qLKyUqtXr1Z5eblOPPHEmD8XsxV9z48//rg2btyoxYsXKz8/X+vWrZvwM/7iiy/q05/+tAKBgLKzs1VbW6trrrlGAwMDE7a7ZcsWLVq0SFVVVeNmvfvuu1VWVqalS5fGvfsewOywQgmkWFdXV8xf7iMjIxPuu+WWW/S1r31NF1xwgf76r/9ahw8f1j333KMPfvCDeuONN1RSUiLpSAC49NJLdfLJJ+u2227ToUOHdPfdd+ull14a9zxJCofD+shHPqJTTz1VX//61/Xss89q06ZNCoVC2rx586Rz7969Ww888MCE+/v7+3X66aerublZV1xxhQKBgF5++WV99atf1YEDB3TXXXfN6PM57rjj9PDDD4/evv/++/WHP/xBd9555+h9J5544qSvv+OOO3To0KGYj3V0dOhjH/uYLrjgAn3mM5/R97//fX3pS19SVlaWPv/5z0uSBgYGdMYZZ2j37t268sorZdu2tm7dqvXr16uzs1N/+7d/O26bl19+udasWaOhoSH9/Oc/15YtW5STk6Obb75ZkvTOO+/oRz/6kT796U/Ltm0dOnRI9913n04//XT9z//8j6qrq2f0+Xjl4Ycf1o4dO1Ky7VtuuUWWZen6669XS0uL7rrrLp155pn63e9+p9zcXElH/sHU39+vL33pSyovL9evf/1r3XPPPdq3b5+2bt06uq3vfe97uu6663TuuefqIx/5iLZs2aLm5mYdPHhQvb29uvnmm/XYY4/p0ksv1bJly3Taaael5D0BC54LICUefPBBV9KUXytXrhx9fkNDg+v3+91bbrll3HZ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UtXX14+u1GdnZ+ucc87Rf/zHf6Tk/QBglzeQcn/xF3+h973vfRPujwayqF27dsl1XS1fvjzmdjIzMyVJjY2NkmKfOXvsscdOqGjx+XxyHGfcffX19ZKOHBcYy4YNG7RmzRqde+6548JodM4333xz0hM2Wlpaxt3etGlTzGBSVVUV8/Xx2rNnj+677z7967/+67hgPVZ1dbXy8/PH3Tf2vZ966qlqbGzU8uXLJwTn4447TtKfP++oq666SlddddXo7UsvvVTXXHPN6O1IJKK7775b3/rWt7Rnz55x4bm8vHzCjNFd7/E488wz437u2J+PyspKXXbZZbrpppvk9/unfF1XV5duvfVW/d3f/V3Cf0eTOfpn3LIsLVu2bNzPY1NTk2644QY99dRT6ujomDCjpNHjLmtqaqb9njU1Nert7VVnZ+e4Q0IAJAeBEjBEJBKRZVl65plnYv7SLygomJM5tm3bpueee06vvPJKzMcjkYg+/OEP6+///u9jPh4NbFGXX365Pv3pT4+777LLLkt4zn/4h3/Q8uXLdckll+jFF19MeHvxuu6663TWWWcpHA7rrbfeGj3B6cEHH5R0pBz8a1/7mj7/+c/r5ptvVllZmXw+n77yla+MO2kp6oYbbtCaNWvG3fdXf/VXMb/3N7/5zXGfb3d3tz75yU/GfO4PfvADFRUVqb+/X08++aRuueUWFRUVTfr3FnX77bfL5/PpuuuuU1tb25TPTZVwOKwPf/jDam9v1/XXX69jjz1W+fn5am5u1vr160c/x8HBwRlve2BggEAJpACBEjDEMcccI9d1Zdv2hFA2Vl1dnSTp7bff1l/+5V+Oe+ztt98efTwqEononXfeGbfNnTt3Sjpytu9Yrutqw4YNOv/883XqqadOOmdvb2/cq2XLly+f8NyjVw1n6o033tBjjz2mH/3oR1OuuO3fv199fX3jvt/R772urk5vvvmmIpHIuFXKP/7xj6OPj3X88cePvp+zzz5bQ0ND2rhxo2655RZVV1friSee0Nq1a/Vv//Zv417
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"image/png": "iVBORw0KG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qalWjx49rIIFC1rlypWzVq9ebQUEBFgvvfSS1adPHyswMNCqUKGCtXz58ix/HsHBwZbdbr/+/hMnTtxw2aDExETr2WeftcqUKWP5+vpaJUqUsFq2bGmtWLEiS1+v6dOnW3fddZdVuHBhKyQkxHriiSesu+++21q4cKFVqlQpq1ixYjdcCsiy/rhs0LvvvmuVKlXKKlCggNWkSRNrx44dVvPmza3mzZtff9yfl/wpVaqUFR8ff8Ma+stlg+bPn2/df//91vjx42/4XP+6xl+/zln9fgBARmyWxa+gAHLGrFmz9MorrygiIiJXb9EYGBioZ5555oY72zizNm3a6IcffrjhVe4A4E7YQwkAAACHUCgBAADgEAolAAAAHMIeSgAAADiECSUAAAAcQqEEAACAQyiUAAAAcAiFEgAAAA6hUAIAAMAhFEoAAAA4hEIJAAAAh1AoAQAA4BAKJQAAABxCoQQAAIBDKJQAAABwCIUSAAAADqFQAgAAwCEUSgAAADiEQgkAAACHUCgBAADgEAolAAAAHEKhBAAAgEMolAAAAHAIhRIAAAAOoVACAADAIRRKAAAAOIRCCQAAAIdQKAEAAOAQCiUAAAAcQqEEAACAQyiUAAAAcAiFEgAAAA6hUAIAAMAhFEoAAAA4hEIJAAAAh1AoAQAA4BAf0wEAAMgp8clp+ulCvFLS7PL18VL5oAA
"text/plain": [
"<Figure size 640x480 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Генерируем ориентированные и неориентированные графы\n",
"G_directed = nx.DiGraph()\n",
"G_undirected = nx.Graph()\n",
"\n",
"# Добавляем ребра в ориентированный граф\n",
"G_directed.add_edges_from([(1, 2), (2, 3), (3, 2), (4, 2)])\n",
"\n",
"# Добавляем ребра в неориентированный граф\n",
"G_undirected.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1)])\n",
"\n",
"# Считываем граф из файла\n",
"G_from_file = nx.read_edgelist('Задание_9_graph.txt', nodetype=int)\n",
"\n",
"# Визуализируем графы\n",
"nx.draw(G_directed, with_labels=True, font_weight='bold')\n",
"plt.title('Ориентированный Граф')\n",
"plt.show()\n",
"\n",
"nx.draw(G_undirected, with_labels=True, font_weight='bold')\n",
"plt.title('Неориентированный Граф')\n",
"plt.show()\n",
"\n",
"nx.draw(G_from_file, with_labels=True, font_weight='bold')\n",
"plt.title('Граф из файла')\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 45,
"id": "8eea3b07",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Матрица смежности ориентированного графа:\n",
"[[0 1 0 0]\n",
" [0 0 1 0]\n",
" [0 1 0 0]\n",
" [0 1 0 0]]\n",
"Матрица смежности неориентированного графа:\n",
"[[0 1 0 1]\n",
" [1 0 1 0]\n",
" [0 1 0 1]\n",
" [1 0 1 0]]\n",
"Матрица инцидентности ориентированного графа:\n",
"[[1. 0. 0. 0.]\n",
" [1. 1. 1. 1.]\n",
" [0. 1. 1. 0.]\n",
" [0. 0. 0. 1.]]\n",
"Матрица инцидентности неориентированного графа:\n",
"[[1. 1. 0. 0.]\n",
" [1. 0. 1. 0.]\n",
" [0. 0. 1. 1.]\n",
" [0. 1. 0. 1.]]\n",
"Степени вершин ориентированного графа:\n",
"[(1, 0), (2, 3), (3, 1), (4, 0)]\n",
"Степени вершин неориентированного графа:\n",
"[(1, 2), (2, 2), (3, 2), (4, 2)]\n",
"Список ребер ориентированного графа:\n",
"[(1, 2), (2, 3), (3, 2), (4, 2)]\n",
"Список ребер неориентированного графа:\n",
"[(1, 2), (1, 4), (2, 3), (3, 4)]\n",
"Список вершин ориентированного графа:\n",
"[1, 2, 3, 4]\n",
"Список вершин неориентированного графа:\n",
"[1, 2, 3, 4]\n"
]
}
],
"source": [
"# Получаем матрицы смежности и инцидентности\n",
"print(\"Матрица смежности ориентированного графа:\")\n",
"print(nx.adjacency_matrix(G_directed).todense())\n",
"\n",
"print(\"Матрица смежности неориентированного графа:\")\n",
"print(nx.adjacency_matrix(G_undirected).todense())\n",
"\n",
"print(\"Матрица инцидентности ориентированного графа:\")\n",
"print(nx.incidence_matrix(G_directed).todense())\n",
"\n",
"print(\"Матрица инцидентности неориентированного графа:\")\n",
"print(nx.incidence_matrix(G_undirected).todense())\n",
"\n",
"# Выводим степени вершин каждого графа\n",
"print(\"Степени вершин ориентированного графа:\")\n",
"print(G_directed.in_degree())\n",
"\n",
"print(\"Степени вершин неориентированного графа:\")\n",
"print(G_undirected.degree())\n",
"\n",
"# Выводим списки ребер\n",
"print(\"Список ребер ориентированного графа:\")\n",
"print(G_directed.edges())\n",
"\n",
"print(\"Список ребер неориентированного графа:\")\n",
"print(G_undirected.edges())\n",
"\n",
"# Выводим списки вершин\n",
"print(\"Список вершин ориентированного графа:\")\n",
"print(G_directed.nodes())\n",
"\n",
"print(\"Список вершин неориентированного графа:\")\n",
"print(G_undirected.nodes())"
]
},
{
"cell_type": "markdown",
"id": "2087767b",
"metadata": {},
"source": [
"**Задание 2.** Проверить любой из графов из задания 1 на наличие Эйлерова цикла, эйлерова пути, гамильтонова цикла."
]
},
{
"cell_type": "code",
"execution_count": 63,
"id": "0e8216f7",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Граф содержит Эйлеров цикл.\n",
"Граф содержит Эйлеров путь.\n",
"Граф содержит Гамильтонов цикл, цикл: (1, 2, 3, 4)\n"
]
}
],
"source": [
"import itertools\n",
"\n",
"\n",
"# Проверка на наличие Эйлерова цикла\n",
"if nx.is_eulerian(G_undirected):\n",
" print(\"Граф содержит Эйлеров цикл.\")\n",
"else:\n",
" print(\"Граф не содержит Эйлеров цикл.\")\n",
"\n",
"# Проверка на наличие Эйлерова пути\n",
"if nx.has_eulerian_path(G_undirected):\n",
" print(\"Граф содержит Эйлеров путь.\")\n",
"else:\n",
" print(\"Граф не содержит Эйлеров путь.\")\n",
"\n",
"# Проверка на наличие Гамильтонова цикла\n",
"def is_hamiltonian(graph: any) -> None:\n",
" for p in itertools.permutations(list(graph.nodes())):\n",
" if all(p[i] in graph[p[i - 1]] for i in range(len(p))) and p[0] in graph[p[-1]]:\n",
" print(f\"Граф содержит Гамильтонов цикл, цикл: {p}\")\n",
" return\n",
"\n",
"is_hamiltonian(G_undirected)"
]
},
{
"cell_type": "markdown",
"id": "2e168a74",
"metadata": {},
"source": [
"**Задание 3.** Подсчитать количество циклов в любом из графов из задания 1."
]
},
{
"cell_type": "code",
"execution_count": 67,
"id": "2ffaa940",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Количество циклов: 1\n"
]
}
],
"source": [
"from networkx.algorithms import cycle_basis\n",
"\n",
"# Находим все циклы в графе\n",
"cycles = cycle_basis(G_undirected)\n",
"\n",
"# Подсчет количества циклов\n",
"number_of_cycles = len(cycles)\n",
"\n",
"# Выводим количество циклов\n",
"print(f'Количество циклов: {number_of_cycles}')"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.0"
}
},
"nbformat": 4,
"nbformat_minor": 5
}