diff --git a/.ipynb_checkpoints/ED2-checkpoint.ipynb b/.ipynb_checkpoints/ED2-checkpoint.ipynb new file mode 100644 index 0000000..39faabb --- /dev/null +++ b/.ipynb_checkpoints/ED2-checkpoint.ipynb @@ -0,0 +1,582 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 50, + "id": "d54522d8", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "" + ], + "text/plain": [ + "" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "from IPython.display import display, HTML\n", + "display(HTML(\"\"))" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "8b003e19", + "metadata": {}, + "outputs": [], + "source": [ + "class Vertice:\n", + " \n", + " def __init__(self, valor, direcionado=True):\n", + " self.__valor = valor\n", + " self.__direcionado = direcionado\n", + " self.__arestas = set()\n", + " \n", + " def getValor(self):\n", + " return self.__valor\n", + " \n", + " def setValor(self, valor):\n", + " self.__valor = valor\n", + " \n", + " def getArestas(self):\n", + " return self.__arestas\n", + " \n", + " def adicionarAresta(self, aresta):\n", + " self.__arestas.add(aresta)\n", + " \n", + " def getArestasSaida(self):\n", + " if self.__direcionado == False:\n", + " return self.__arestas\n", + " arestasDeSaida = []\n", + " for aresta in self.__arestas:\n", + " if aresta.getvOrigem() == self:\n", + " arestasDeSaida.append(aresta)\n", + " return arestasDeSaida\n", + " \n", + " def getArestasEntrada(self):\n", + " if self.__direcionado == False:\n", + " return self.__arestas\n", + " arestasSaida = []\n", + " for aresta in self.__arestas:\n", + " if aresta.getvDestino() == self:\n", + " arestasSaida.append(aresta)\n", + " return arestasSaida\n", + " \n", + " def getGrau(self):\n", + " return len(self.getArestasSaida())+ len(self.getArestasEntrada())\n", + " \n", + " def getAdjacentes(self, v):\n", + " listaVerticesAdjacentes = []\n", + " for arestas_de_saida in v.getArestasSaida():\n", + " listaVerticesAdjacentes.append(arestas_de_saida.getvDestino())\n", + " return listaVerticesAdjacentes" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "5c3677e7", + "metadata": {}, + "outputs": [], + "source": [ + "class Aresta:\n", + " def __init__(self, vOrigem, vDestino, peso, direcionada=True):\n", + " self.__vOrigem = vOrigem\n", + " self.__vDestino = vDestino\n", + " self.__peso = peso\n", + " self.__direcionada = direcionada\n", + " self.__vOrigem.adicionarAresta(self)\n", + " self.__vDestino.adicionarAresta(self)\n", + " \n", + " def getvOrigem(self):\n", + " return self.__vOrigem\n", + " def getvDestino(self):\n", + " return self.__vDestino\n", + " def getValor(self):\n", + " return self.__peso" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "d3d8fa70", + "metadata": {}, + "outputs": [], + "source": [ + "from collections import deque\n", + "class Grafo:\n", + " def __init__(self, direcionado=True):\n", + " self.__vertices = set()\n", + " self.__arestas = set()\n", + " self.__direcionado = direcionado\n", + " \n", + " def setVertices(self, vertices):\n", + " self.__vertices = vertices\n", + " \n", + " def setArestas(self, arestas):\n", + " self.__arestas = arestas\n", + " \n", + " def getVertices(self):\n", + " return self.__vertices\n", + " \n", + " def getVerticeByValor(self, valor):\n", + " for v in self.__vertices:\n", + " if v.getValor() == valor:\n", + " return v\n", + " return None\n", + " \n", + " def getArestas(self):\n", + " return self.__arestas\n", + " \n", + " def adicionarVertice(self, valor):\n", + " if self.buscarPorValor(valor) != valor:\n", + " self.__vertices.add(Vertice(valor))\n", + " return True\n", + " return False\n", + " \n", + " def adicionarAresta(self, origem, destino, peso = 1, direcionada = True):\n", + " try:\n", + " verticeOrigem = self.getVerticeByValor(origem)\n", + " verticeDestino = self.getVerticeByValor(destino)\n", + " if (verticeOrigem or verticeDestino) is None: \n", + " print(\"Nao ha no grafo, vertices de origem ou de destino com os valores informados.\")\n", + " self.__arestas.add(Aresta(verticeOrigem, verticeDestino, peso, direcionada))\n", + " except AttributeError as error:\n", + " print(\"Nao ha no grafo, vertices de origem ou de destino com os valores informados.\")\n", + " \n", + "\n", + " \n", + " def checkHandShakingLemma(self):\n", + " somaGraus = 0\n", + " for v in self.getVertices():\n", + " somaGraus+= v.getGrau()\n", + " if somaGraus == len(self.getArestas())*2:\n", + " return True\n", + " else:\n", + " return False\n", + " \n", + " def dfs(self, graph, v, visitados=[]):\n", + " if v not in visitados:\n", + " visitados.append(v) \n", + " if len(v.getAdjacentes(v)) == 0: \n", + " self.dfs(graph, next(iter(graph.getVertices())), visitados) \n", + " else: \n", + " for adjacente in v.getAdjacentes(v):\n", + " if adjacente not in visitados:\n", + " self.dfs(graph, adjacente, visitados) \n", + " return visitados\n", + " \n", + " def bfs(self, v, visitados = [], fila = deque([])):\n", + " fila.append(v) \n", + " if v not in visitados: \n", + " visitados.append(v) \n", + " while fila: \n", + " vertice = fila.popleft() \n", + " if len(vertice.getArestasSaida()) == 0:\n", + " self.bfs(next(iter(self.getVertices())), visitados, fila) \n", + " else:\n", + " for adjacente in vertice.getAdjacentes(v): \n", + " if adjacente not in visitados:\n", + " visitados.append(adjacente) \n", + " self.bfs(adjacente, visitados, fila) \n", + " return visitados \n", + " \n", + " def buscarPorValor(self, valor):\n", + " for v in self.bfs(next(iter(self.getVertices())), visitados = [], fila = deque([])):\n", + " if valor == v.getValor():\n", + " return valor\n", + " return None\n", + " \n", + " def delverte(self):\n", + " \n", + " \n", + " for i in range(self, origem, destino, peso = 1, direcionada = True):\n", + " verticeOrigem = self.getVerticeByValor(origem)\n", + " verticeDestino = self.getVerticeByValor(destino)\n", + " if (verticeOrigem or verticeDestino) is None:\n", + " self.__arestas(Aresta(verticeOrigem, verticeDestino, peso, direcionada))\n", + " \n", + " \n", + " def removerVertice(self, vertice):\n", + " listaArestas = []\n", + " vertice = self.getVerticeByValor(vertice)\n", + " if vertice in self.getVertices():\n", + " for a in self.getArestas():\n", + " if (a.getvOrigem() == vertice) or (a.getvDestino() == vertice):\n", + " listaArestas.append(a)\n", + " for a in listaArestas:\n", + " self.__arestas.remove(a)\n", + " self.getVertices().remove(vertice)\n", + " return True\n", + " else:\n", + " return False\n", + " \n", + " def removerAresta(self, origem, destino, peso, direcionada=True):\n", + " Origem = self.getVerticeByValor(origem)\n", + " Destino = self.getVerticeByValor(destino)\n", + " remover_lista = list()\n", + " if (Destino or Origem) is not None: \n", + " for a in self.getArestas():\n", + " if (a.getvOrigem() == Origem) and (a.getvDestino() == Destino) and a.getValor() == peso:\n", + " remover_lista.append(a)\n", + " [self.getArestas().remove(a) for a in remover_lista]\n", + " return True\n", + " return False\n", + " \n", + " def Euler(self, graph):\n", + " impar = 0\n", + " for v in graph.getVertices():\n", + " if v.getGrau() %2 != 0:\n", + " impar += 1\n", + " if impar != 0 >= 2:\n", + " return True \n", + " else:\n", + " return False\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "91b986a7", + "metadata": {}, + "outputs": [], + "source": [ + "v1 = Vertice(1)\n", + "v2 = Vertice(2)\n", + "v3 = Vertice(3)\n", + "v4 = Vertice(4)\n", + "v5 = Vertice(5)\n", + "a1 = Aresta( v1, v2, 10, True )\n", + "a2 = Aresta( v2, v3, 20, True )\n", + "a3 = Aresta( v3, v4, 30, True )\n", + "a4 = Aresta( v4, v1, 40, True )\n", + "a5 = Aresta( v4, v5, 50, True )" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "2db17f8a", + "metadata": {}, + "outputs": [], + "source": [ + "G = Grafo()\n", + "G.setVertices({v1, v2, v3, v4, v5})\n", + "G.setArestas({a1, a2, a3, a4, a5})" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "13453065", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Nao ha no grafo, vertices de origem ou de destino com os valores informados.\n" + ] + } + ], + "source": [ + "G.adicionarVertice(7)\n", + "G.adicionarAresta(5, 15, 10, True)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "28e99364", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "4\t5\t3\t1\t7\t2\t" + ] + } + ], + "source": [ + "for v in G.getVertices():\n", + " print(v.getValor(), end=\"\\t\")" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "29d5dcfe", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2 ---> 3\t1 ---> 2\t4 ---> 5\t3 ---> 4\t4 ---> 1\t" + ] + } + ], + "source": [ + "for a in G.getArestas():\n", + " print(a.getvOrigem().getValor(), end=\"\")\n", + " print(\" ---> \", end=\"\")\n", + " print(a.getvDestino().getValor(), end=\"\\t\")" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "3ebc1c5d", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "2" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "v1.getGrau()" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "4690659b", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "G.checkHandShakingLemma()" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "1e0f4098", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Busca em profundidade, iniciando com o vértice 1:\n", + "1\t2\t3\t4\t6\t5\t\n", + ".................................................\n", + "Busca em profundidade, iniciando com o vértice 5:\n", + "5\t1\t2\t3\t4\t6\t\n", + ".................................................\n", + "Busca em profundidade, iniciando com o vértice 4:\n", + "4\t1\t2\t3\t6\t5\t\n", + ".................................................\n", + "Busca em profundidade, iniciando com o vértice 2:\n", + "2\t3\t4\t1\t6\t5\t\n", + ".................................................\n", + "Busca em profundidade, iniciando com o vértice 3:\n", + "3\t4\t1\t2\t6\t5\t\n", + ".................................................\n", + "Busca em profundidade, iniciando com o vértice 6:\n", + "6\t1\t2\t3\t4\t5\t\n", + ".................................................\n" + ] + } + ], + "source": [ + "v1 = Vertice(1)\n", + "v2 = Vertice(2)\n", + "v3 = Vertice(3)\n", + "v4 = Vertice(4)\n", + "v5 = Vertice(5)\n", + "v6 = Vertice(6)\n", + "a1 = Aresta( v1, v2, 10, True )\n", + "a2 = Aresta( v2, v3, 20, True )\n", + "a3 = Aresta( v3, v4, 30, True )\n", + "a4 = Aresta( v4, v1, 40, True )\n", + "a5 = Aresta( v4, v5, 50, True ) \n", + "a6 = Aresta( v4, v6, 60, True ) \n", + "G = Grafo()\n", + "G.setVertices({v1, v2, v3, v4, v5,v6})\n", + "G.setArestas({a1, a2, a3, a4, a5, a6})\n", + "for vertice in G.getVertices():\n", + " print(f\"Busca em profundidade, iniciando com o vértice {vertice.getValor()}:\")\n", + " for v in G.dfs(G, vertice, visitados=[]):\n", + " print(str(v.getValor())+\"\\t\", end=\"\")\n", + " print(\"\\n.................................................\") " + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "b7459764", + "metadata": { + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Busca em largura, iniciando com o vértice 4:\n", + "4\t6\t5\t1\t2\t3\t\n", + "............................................\n", + "Busca em largura, iniciando com o vértice 1:\n", + "1\t2\t3\t4\t6\t5\t\n", + "............................................\n", + "Busca em largura, iniciando com o vértice 2:\n", + "2\t3\t4\t6\t5\t1\t\n", + "............................................\n", + "Busca em largura, iniciando com o vértice 6:\n", + "6\t4\t5\t1\t2\t3\t\n", + "............................................\n", + "Busca em largura, iniciando com o vértice 3:\n", + "3\t4\t6\t5\t1\t2\t\n", + "............................................\n", + "Busca em largura, iniciando com o vértice 5:\n", + "5\t4\t6\t1\t2\t3\t\n", + "............................................\n" + ] + } + ], + "source": [ + "v1 = Vertice(1)\n", + "v2 = Vertice(2)\n", + "v3 = Vertice(3)\n", + "v4 = Vertice(4)\n", + "v5 = Vertice(5)\n", + "v6 = Vertice(6)\n", + "a1 = Aresta( v1, v2, 10, True )\n", + "a2 = Aresta( v2, v3, 20, True )\n", + "a3 = Aresta( v3, v4, 30, True )\n", + "a4 = Aresta( v4, v1, 40, True )\n", + "a5 = Aresta( v4, v5, 50, True ) \n", + "a6 = Aresta( v4, v6, 60, True ) \n", + "G = Grafo()\n", + "G.setVertices({v1, v2, v3, v4, v5,v6})\n", + "G.setArestas({a1, a2, a3, a4, a5, a6})\n", + "for vertice in G.getVertices():\n", + " print(f\"Busca em largura, iniciando com o vértice {vertice.getValor()}:\")\n", + " for v in G.bfs(vertice, visitados = [], fila = deque([])):\n", + " print(str(v.getValor())+\"\\t\", end=\"\")\n", + " print(\"\\n............................................\") " + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "b29de58e", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "não é um grafo euleriano\n" + ] + } + ], + "source": [ + "if G.Euler(G):\n", + " print(\"é um grafo euleriano\")\n", + "else:\n", + " print(\"não é um grafo euleriano\")" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "30ca64af", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Valor procurado: 7\n", + "7 não encontrado no grafo\n" + ] + } + ], + "source": [ + "valor = int(input(\"Valor procurado: \"))\n", + "if G.buscarPorValor(valor) == None:\n", + " print(f\"{valor} não encontrado no grafo\")\n", + "else:\n", + " print(f\"{valor} encontrado no grafo\")" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "267a4d22", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "WindowsPath('C:/Users/ifg/ED2')" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import pathlib\n", + "pathlib.Path().resolve()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c954d113", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "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.9.7" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/Cedulas.txt b/Cedulas.txt new file mode 100644 index 0000000..21bd7ed --- /dev/null +++ b/Cedulas.txt @@ -0,0 +1,10 @@ +moedas = [100, 50, 25, 5, 1] +total = 0 +notas = 130 + +for i in range(len(moedas)): + num_moedas = notas // moedas[i] + notas -= num_moedas * moedas[i] + total += num_moedas + +print(total) \ No newline at end of file diff --git a/ED2.ipynb b/ED2.ipynb index b4a44ba..8b867be 100644 --- a/ED2.ipynb +++ b/ED2.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "code", - "execution_count": 15, + "execution_count": 1, "id": "d54522d8", "metadata": {}, "outputs": [ @@ -26,7 +26,7 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 2, "id": "8b003e19", "metadata": {}, "outputs": [], @@ -34,15 +34,15 @@ "class Vertice:\n", " \n", " def __init__(self, valor, direcionado=True):\n", - " self.__dado = valor\n", + " self.__valor = valor\n", " self.__direcionado = direcionado\n", " self.__arestas = set()\n", " \n", - " def getDado(self):\n", - " return self.__dado\n", + " def getValor(self):\n", + " return self.__valor\n", " \n", - " def setDado(self, valor):\n", - " self.__dado = valor\n", + " def setValor(self, valor):\n", + " self.__valor = valor\n", " \n", " def getArestas(self):\n", " return self.__arestas\n", @@ -60,48 +60,56 @@ " return arestasDeSaida\n", " \n", " def getArestasEntrada(self):\n", - " if self.__direciobado == False:\n", + " if self.__direcionado == False:\n", " return self.__arestas\n", " arestasSaida = []\n", - " for aresta in sel.__arestas:\n", + " for aresta in self.__arestas:\n", " if aresta.getvDestino() == self:\n", " arestasSaida.append(aresta)\n", " return arestasSaida\n", - " " + " \n", + " def getGrau(self):\n", + " return len(self.getArestasSaida())+ len(self.getArestasEntrada())\n", + " \n", + " def getAdjacentes(self, v):\n", + " listaVerticesAdjacentes = []\n", + " for arestas_de_saida in v.getArestasSaida():\n", + " listaVerticesAdjacentes.append(arestas_de_saida.getvDestino())\n", + " return listaVerticesAdjacentes" ] }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 3, "id": "5c3677e7", "metadata": {}, "outputs": [], "source": [ "class Aresta:\n", - " def __init__(self, vOrigem, vDestino, valor, direcionada=True):\n", + " def __init__(self, vOrigem, vDestino, peso, direcionada=True):\n", " self.__vOrigem = vOrigem\n", " self.__vDestino = vDestino\n", - " self.__valor = valor\n", + " self.__peso = peso\n", " self.__direcionada = direcionada\n", " self.__vOrigem.adicionarAresta(self)\n", " self.__vDestino.adicionarAresta(self)\n", " \n", - " \n", " def getvOrigem(self):\n", " return self.__vOrigem\n", " def getvDestino(self):\n", " return self.__vDestino\n", " def getValor(self):\n", - " return self.__valor" + " return self.__peso" ] }, { "cell_type": "code", - "execution_count": 24, + "execution_count": 4, "id": "d3d8fa70", "metadata": {}, "outputs": [], "source": [ + "from collections import deque\n", "class Grafo:\n", " def __init__(self, direcionado=True):\n", " self.__vertices = set()\n", @@ -117,13 +125,123 @@ " def getVertices(self):\n", " return self.__vertices\n", " \n", + " def getVerticeByValor(self, valor):\n", + " for v in self.__vertices:\n", + " if v.getValor() == valor:\n", + " return v\n", + " return None\n", + " \n", " def getArestas(self):\n", - " return self.__arestas" + " return self.__arestas\n", + " \n", + " def adicionarVertice(self, valor):\n", + " if self.buscarPorValor(valor) != valor:\n", + " self.__vertices.add(Vertice(valor))\n", + " return True\n", + " return False\n", + " \n", + " def adicionarAresta(self, origem, destino, peso = 1, direcionada = True):\n", + " try:\n", + " verticeOrigem = self.getVerticeByValor(origem)\n", + " verticeDestino = self.getVerticeByValor(destino)\n", + " if (verticeOrigem or verticeDestino) is None: \n", + " print(\"Nao ha no grafo, vertices de origem ou de destino com os valores informados.\")\n", + " self.__arestas.add(Aresta(verticeOrigem, verticeDestino, peso, direcionada))\n", + " except AttributeError as error:\n", + " print(\"Nao ha no grafo, vertices de origem ou de destino com os valores informados.\")\n", + " \n", + "\n", + " \n", + " def checkHandShakingLemma(self):\n", + " somaGraus = 0\n", + " for v in self.getVertices():\n", + " somaGraus+= v.getGrau()\n", + " if somaGraus == len(self.getArestas())*2:\n", + " return True\n", + " else:\n", + " return False\n", + " \n", + " def dfs(self, graph, v, visitados=[]):\n", + " if v not in visitados:\n", + " visitados.append(v) \n", + " if len(v.getAdjacentes(v)) == 0: \n", + " self.dfs(graph, next(iter(graph.getVertices())), visitados) \n", + " else: \n", + " for adjacente in v.getAdjacentes(v):\n", + " if adjacente not in visitados:\n", + " self.dfs(graph, adjacente, visitados) \n", + " return visitados\n", + " \n", + " def bfs(self, v, visitados = [], fila = deque([])):\n", + " fila.append(v) \n", + " if v not in visitados: \n", + " visitados.append(v) \n", + " while fila: \n", + " vertice = fila.popleft() \n", + " if len(vertice.getArestasSaida()) == 0:\n", + " self.bfs(next(iter(self.getVertices())), visitados, fila) \n", + " else:\n", + " for adjacente in vertice.getAdjacentes(v): \n", + " if adjacente not in visitados:\n", + " visitados.append(adjacente) \n", + " self.bfs(adjacente, visitados, fila) \n", + " return visitados \n", + " \n", + " def buscarPorValor(self, valor):\n", + " for v in self.bfs(next(iter(self.getVertices())), visitados = [], fila = deque([])):\n", + " if valor == v.getValor():\n", + " return valor\n", + " return None\n", + " \n", + " def delverte(self):\n", + " for i in range(self, origem, destino, peso = 1, direcionada = True):\n", + " verticeOrigem = self.getVerticeByValor(origem)\n", + " verticeDestino = self.getVerticeByValor(destino)\n", + " if (verticeOrigem or verticeDestino) is None:\n", + " self.__arestas(Aresta(verticeOrigem, verticeDestino, peso, direcionada))\n", + " \n", + " \n", + " def removerVertice(self, vertice):\n", + " listaArestas = []\n", + " vertice = self.getVerticeByValor(vertice)\n", + " if vertice in self.getVertices():\n", + " for a in self.getArestas():\n", + " if (a.getvOrigem() == vertice) or (a.getvDestino() == vertice):\n", + " listaArestas.append(a)\n", + " for a in listaArestas:\n", + " self.__arestas.remove(a)\n", + " self.getVertices().remove(vertice)\n", + " return True\n", + " else:\n", + " return False\n", + "\n", + " def removerAresta(self, origem, destino, peso, direcionada=True):\n", + " Origem = self.getVerticeByValor(origem)\n", + " Destino = self.getVerticeByValor(destino)\n", + " remover_lista = list()\n", + " if (Destino or Origem) is not None: \n", + " for a in self.getArestas():\n", + " if (a.getvOrigem() == Origem) and (a.getvDestino() == Destino) and a.getValor() == peso:\n", + " remover_lista.append(a)\n", + " [self.getArestas().remove(a) for a in remover_lista]\n", + " return True\n", + " return False\n", + " \n", + "\n", + " def Euler(self, graph):\n", + " impar = 0\n", + " for v in graph.getVertices():\n", + " if v.getGrau() %2 != 0:\n", + " impar += 1\n", + " if impar != 0 >= 2:\n", + " return True \n", + " else:\n", + " return False" ] }, { "cell_type": "code", - "execution_count": 25, + "execution_count": 5, "id": "91b986a7", "metadata": {}, "outputs": [], @@ -132,49 +250,48 @@ "v2 = Vertice(2)\n", "v3 = Vertice(3)\n", "v4 = Vertice(4)\n", + "v5 = Vertice(5)\n", "a1 = Aresta( v1, v2, 10, True )\n", "a2 = Aresta( v2, v3, 20, True )\n", "a3 = Aresta( v3, v4, 30, True )\n", - "a4 = Aresta( v4, v1, 40, True )" + "a4 = Aresta( v4, v1, 40, True )\n", + "a5 = Aresta( v4, v5, 50, True )" ] }, { "cell_type": "code", - "execution_count": 30, + "execution_count": 6, "id": "2db17f8a", "metadata": {}, "outputs": [], "source": [ "G = Grafo()\n", - "G.setVertices({v1, v2, v3, v4})\n", - "G.setArestas({a1, a2, a3, a4})" + "G.setVertices({v1, v2, v3, v4, v5})\n", + "G.setArestas({a1, a2, a3, a4, a5})" ] }, { "cell_type": "code", - "execution_count": 31, - "id": "1c2d3a62", + "execution_count": 7, + "id": "13453065", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "2\n", - "3\n", - "1\n", - "4\n" + "Nao ha no grafo, vertices de origem ou de destino com os valores informados.\n" ] } ], "source": [ - "for v in G.getVertices():\n", - " print(v.getDado())" + "G.adicionarVertice(7)\n", + "G.adicionarAresta(5, 15, 10, True)" ] }, { "cell_type": "code", - "execution_count": 32, + "execution_count": 8, "id": "28e99364", "metadata": {}, "outputs": [ @@ -182,24 +299,505 @@ "name": "stdout", "output_type": "stream", "text": [ - "4 ---> 1\n", - "1 ---> 2\n", - "3 ---> 4\n", - "2 ---> 3\n" + "1\t4\t2\t3\t7\t5\t" + ] + } + ], + "source": [ + "for v in G.getVertices():\n", + " print(v.getValor(), end=\"\\t\")" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "29d5dcfe", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "4 ---> 1\t4 ---> 5\t1 ---> 2\t2 ---> 3\t3 ---> 4\t" ] } ], "source": [ "for a in G.getArestas():\n", - " print(a.getvOrigem().getDado(), end=\"\")\n", + " print(a.getvOrigem().getValor(), end=\"\")\n", " print(\" ---> \", end=\"\")\n", - " print(a.getvDestino().getDado())" + " print(a.getvDestino().getValor(), end=\"\\t\")" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "3ebc1c5d", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "2" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "v1.getGrau()" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "4690659b", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "G.checkHandShakingLemma()" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "1e0f4098", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Busca em profundidade, iniciando com o vértice 2:\n", + "2\t3\t4\t5\t6\t1\t\n", + ".................................................\n", + "Busca em profundidade, iniciando com o vértice 3:\n", + "3\t4\t5\t2\t6\t1\t\n", + ".................................................\n", + "Busca em profundidade, iniciando com o vértice 4:\n", + "4\t5\t2\t3\t6\t1\t\n", + ".................................................\n", + "Busca em profundidade, iniciando com o vértice 6:\n", + "6\t2\t3\t4\t5\t1\t\n", + ".................................................\n", + "Busca em profundidade, iniciando com o vértice 5:\n", + "5\t2\t3\t4\t6\t1\t\n", + ".................................................\n", + "Busca em profundidade, iniciando com o vértice 1:\n", + "1\t2\t3\t4\t5\t6\t\n", + ".................................................\n" + ] + } + ], + "source": [ + "v1 = Vertice(1)\n", + "v2 = Vertice(2)\n", + "v3 = Vertice(3)\n", + "v4 = Vertice(4)\n", + "v5 = Vertice(5)\n", + "v6 = Vertice(6)\n", + "a1 = Aresta( v1, v2, 10, True )\n", + "a2 = Aresta( v2, v3, 20, True )\n", + "a3 = Aresta( v3, v4, 30, True )\n", + "a4 = Aresta( v4, v1, 40, True )\n", + "a5 = Aresta( v4, v5, 50, True ) \n", + "a6 = Aresta( v4, v6, 60, True ) \n", + "G = Grafo()\n", + "G.setVertices({v1, v2, v3, v4, v5,v6})\n", + "G.setArestas({a1, a2, a3, a4, a5, a6})\n", + "for vertice in G.getVertices():\n", + " print(f\"Busca em profundidade, iniciando com o vértice {vertice.getValor()}:\")\n", + " for v in G.dfs(G, vertice, visitados=[]):\n", + " print(str(v.getValor())+\"\\t\", end=\"\")\n", + " print(\"\\n.................................................\") " + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "b7459764", + "metadata": { + "scrolled": true + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Busca em largura, iniciando com o vértice 3:\n", + "3\t4\t1\t2\t5\t6\t\n", + "............................................\n", + "Busca em largura, iniciando com o vértice 6:\n", + "6\t3\t4\t1\t2\t5\t\n", + "............................................\n", + "Busca em largura, iniciando com o vértice 2:\n", + "2\t3\t4\t1\t5\t6\t\n", + "............................................\n", + "Busca em largura, iniciando com o vértice 5:\n", + "5\t3\t4\t1\t2\t6\t\n", + "............................................\n", + "Busca em largura, iniciando com o vértice 4:\n", + "4\t1\t2\t3\t5\t6\t\n", + "............................................\n", + "Busca em largura, iniciando com o vértice 1:\n", + "1\t2\t3\t4\t5\t6\t\n", + "............................................\n" + ] + } + ], + "source": [ + "v1 = Vertice(1)\n", + "v2 = Vertice(2)\n", + "v3 = Vertice(3)\n", + "v4 = Vertice(4)\n", + "v5 = Vertice(5)\n", + "v6 = Vertice(6)\n", + "a1 = Aresta( v1, v2, 10, True )\n", + "a2 = Aresta( v2, v3, 20, True )\n", + "a3 = Aresta( v3, v4, 30, True )\n", + "a4 = Aresta( v4, v1, 40, True )\n", + "a5 = Aresta( v4, v5, 50, True ) \n", + "a6 = Aresta( v4, v6, 60, True ) \n", + "G = Grafo()\n", + "G.setVertices({v1, v2, v3, v4, v5,v6})\n", + "G.setArestas({a1, a2, a3, a4, a5, a6})\n", + "for vertice in G.getVertices():\n", + " print(f\"Busca em largura, iniciando com o vértice {vertice.getValor()}:\")\n", + " for v in G.bfs(vertice, visitados = [], fila = deque([])):\n", + " print(str(v.getValor())+\"\\t\", end=\"\")\n", + " print(\"\\n............................................\") " + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "b29de58e", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "não é um grafo euleriano\n" + ] + } + ], + "source": [ + "if G.Euler(G):\n", + " print(\"é um grafo euleriano\")\n", + "else:\n", + " print(\"não é um grafo euleriano\")" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "30ca64af", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Valor procurado: 4\n", + "4 encontrado no grafo\n" + ] + } + ], + "source": [ + "valor = int(input(\"Valor procurado: \"))\n", + "if G.buscarPorValor(valor) == None:\n", + " print(f\"{valor} não encontrado no grafo\")\n", + "else:\n", + " print(f\"{valor} encontrado no grafo\")" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "267a4d22", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "WindowsPath('C:/Users/ifg/ED2')" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import pathlib\n", + "pathlib.Path().resolve()" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "1dd0997c", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "G.removerVertice(4)" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "c954d113", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "G.removerAresta(1, 2, True)" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "cdff3f83", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1: 2 -> 3 -> 4 -> \n", + "2: 3 -> \n", + "3: \n", + "4: \n" + ] + } + ], + "source": [ + "class Grafo:\n", + "\n", + " def __init__(self, vertices):\n", + " self.vertices = vertices\n", + " self.grafo = [[] for i in range(self.vertices)]\n", + "\n", + " def adicionaAresta(self, u, v):\n", + " self.grafo[u-1].append(v)\n", + "\n", + "\n", + " def mostraLista(self):\n", + " for i in range(self.vertices):\n", + " print(f'{i+1}:', end=' ')\n", + " for j in self.grafo[i]:\n", + " print(f'{j} ->', end=' ')\n", + " print('')\n", + "\n", + "g = Grafo(4)\n", + "\n", + "g.adicionaAresta(1,2)\n", + "g.adicionaAresta(1,3)\n", + "g.adicionaAresta(1,4)\n", + "g.adicionaAresta(2,3)\n", + "\n", + "g.mostraLista()" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "d3c0b8e0", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'a': 0, 'b': -1, 'c': 3, 'd': -2, 'e': 1}\n", + "{'a': 0, 'b': 10, 'c': 2, 'd': 3}\n" + ] + } + ], + "source": [ + "def bellman_ford(graph, source):\n", + " distancia, antecessor = dict(), dict()\n", + " for node in graph:\n", + " distancia[node], antecessor[node] = float('inf'), None\n", + " distancia[source] = 0\n", + "\n", + " for _ in range(len(graph) - 1):\n", + " for node in graph:\n", + " for neighbour in graph[node]:\n", + " if distancia[neighbour] > distancia[node] + graph[node][neighbour]:\n", + " distancia[neighbour], antecessor[neighbour] = distancia[node] + graph[node][neighbour], node\n", + "\n", + " for node in graph:\n", + " for neighbour in graph[node]:\n", + " assert distancia[neighbour] <= distancia[node] + graph[node][neighbour], \"Negativo ciclo.\"\n", + " \n", + " return distancia, antecessor\n", + " \n", + "if __name__ == '__main__':\n", + " graph = {\n", + " 'a': {'b': -1, 'c': 4},\n", + " 'b': {'c': 5, 'd': 3, 'e': 2},\n", + " 'c': {},\n", + " 'd': {'b': 2, 'c': 5},\n", + " 'e': {'d': -3}\n", + " }\n", + "\n", + " distancia, antecessor = bellman_ford(graph, source='a')\n", + "\n", + " print (distancia)\n", + " \n", + " graph = {\n", + " 'a': {'c': 2},\n", + " 'b': {'a': 2},\n", + " 'c': {'b': 8, 'd': 1},\n", + " 'd': {'a': 6},\n", + " }\n", + " \n", + " distancia, antecessor = bellman_ford(graph, source='a')\n", + "\n", + " print (distancia)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "afdafed7", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0, 0.8, 0.3, 1.1, 2.3, 0.2]\n" + ] + } + ], + "source": [ + "import heapq\n", + "\n", + "\n", + "class Grafo():\n", + "\n", + " def __init__(self, arestas: list):\n", + " self.adj = [[] for _ in range(len(arestas))]\n", + " self.dist = [999 for _ in range(len(arestas))]\n", + " self.adiciona_arestas(arestas)\n", + "\n", + " def adiciona_arestas(self, arestas: list) -> None:\n", + " for i in range(len(arestas)):\n", + " for j in range(len(arestas[i])):\n", + " self.__adiciona_aresta(i, arestas[i][j])\n", + "\n", + " def __adiciona_aresta(self, u: int, v: int) -> None:\n", + " if v[0] not in self.adj[u]:\n", + " self.adj[u].append([v[1], v[0]])\n", + "\n", + " def _peso_entre_u_e_v(self, u: int, v: int) -> float:\n", + " for vertice in self.adj[v[1]]:\n", + " if vertice[1] == u:\n", + " return vertice[0]\n", + "\n", + " def dijkstra(self, start: int) -> list:\n", + " distancia = self.dist.copy()\n", + " S = set() \n", + " distancia[start] = 0\n", + "\n", + " while True:\n", + " V = set([(i, distancia[i]) for i in range(len(self.adj))])\n", + " diferenca_de_conjuntos = list(V.difference(S))\n", + " if not diferenca_de_conjuntos:\n", + " break\n", + "\n", + " heapq.heapify(diferenca_de_conjuntos)\n", + " u, distancia_u = heapq.heappop(diferenca_de_conjuntos)\n", + "\n", + " S.add((u, distancia[u]))\n", + " for v in self.adj[u]:\n", + " if distancia[v[1]] > distancia_u + self._peso_entre_u_e_v(u, v):\n", + " distancia[v[1]] = distancia_u + \\\n", + " self._peso_entre_u_e_v(u, v)\n", + "\n", + " return distancia\n", + "\n", + "\n", + "arestas = [[[1, 2], [2, 0.3], [5, 0.4]], \n", + " [[0, 1], [2, 0.5]], \n", + " [[0, 0.3], [1, 0.5], [3, 1.2], [4, 1]], \n", + " [[2, 1.5], [4, 1.2], [5, 0.9]], \n", + " [[2, 2], [3, 1.5]], \n", + " [[0, 0.2], [3, 0.]]\n", + " ]\n", + "\n", + "grafo = Grafo(arestas)\n", + "print(grafo.dijkstra(0))" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "c980535b", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "3\n" + ] + } + ], + "source": [ + "moedas = [100, 50, 25, 5, 1]\n", + "total = 0\n", + "troco = 130\n", + "\n", + "for i in range(len(moedas)):\n", + " num_moedas = troco // moedas[i]\n", + " troco -= num_moedas * moedas[i]\n", + " total += num_moedas\n", + "\n", + "print(total)" ] }, { "cell_type": "code", "execution_count": null, - "id": "6fd4c082", + "id": "da4ee43a", "metadata": {}, "outputs": [], "source": [] @@ -221,7 +819,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.7.12" + "version": "3.9.7" } }, "nbformat": 4, diff --git a/Floyd Warshall.py b/Floyd Warshall.py new file mode 100644 index 0000000..0769b7a --- /dev/null +++ b/Floyd Warshall.py @@ -0,0 +1,37 @@ +# Algoritmo Floyd Warshall em python + +# O número de vértices +nV = 4 + +INF = 999 + + +# Implementação do algoritmo +def floyd_warshall(G): + distancia = list(map(lambda i: list(map(lambda j: j, i)), G)) + + # Adiciona vértices individualmente + for k in range(nV): + for i in range(nV): + for j in range(nV): + distancia[i][j] = min(distancia[i][j], distancia[i][k] + distancia[k][j]) + print_solucao(distancia) + + +# Imprimindo a solução +def print_solucao(distancia): + for i in range(nV): + for j in range(nV): + if(distancia[i][j] == INF): + print("INF", end=" ") + else: + print(distancia[i][j], end=" ") + print(" ") + + +G = [[0, 3, 4, INF], + [INF, 0, INF, 5], + [INF, INF, 0, 3], + [8, INF, INF, 0]] + +floyd_warshall(G) \ No newline at end of file diff --git a/Mochila.txt b/Mochila.txt new file mode 100644 index 0000000..a78740f --- /dev/null +++ b/Mochila.txt @@ -0,0 +1,39 @@ +class Mochila: + def __init__(self, peso_objeto = 20): + self.__peso_objeto = peso_objeto + self.__itens_adicionados = list() + + + def adicionar_itens(self, objetos = list()): + peso_disponivel = self.__peso_objeto + pos = 0 + objetos.sort(key = lambda i:i.getM(), reverse = True) + while peso_disponivel != 0: + if objetos[pos].getPeso() <= peso_disponivel: + self.__itens_adicionados.append(objetos[pos]) + peso_disponivel -= objetos[pos].getPeso() + else: + pos += 1 + + def getItems(self): + return self.__itens_adicionados +class Item: + def __init__(self, nome_item, valor_item, peso_item): + self.__nome_item = nome_item + self.__valor_item = valor_item + self.__peso_item = peso_item + self.__m = valor_item / peso_item + + def getM(self): + return self.__m + + def getPeso(self): + return self.__peso_item + + def getNome(self): + return self.__nome_item +M = Mochila() +M.adicionar_itens([Item("Ouro", 100, 5), Item("Prata", 20, 2), Item("Diamante", 200, 7), Item("Ferro", 5, 1),]) + +for i in M.getItems(): + print(i.getNome()) \ No newline at end of file diff --git a/kruskal.txt b/kruskal.txt new file mode 100644 index 0000000..147fd7b --- /dev/null +++ b/kruskal.txt @@ -0,0 +1,64 @@ +class Graph: + def __init__(self, vertices): + self.V = vertices + self.graph = [] + + def add_edge(self, u, v, w): + self.graph.append([u, v, w]) + + + def find(self, parente, i): + if parente[i] == i: + return i + return self.find(parente, parente[i]) + + def apply_union(self, parente, rank, x, y): + xroot = self.find(parente, x) + yroot = self.find(parente, y) + if rank[xroot] < rank[yroot]: + parente[xroot] = yroot + elif rank[xroot] > rank[yroot]: + parente[yroot] = xroot + else: + parente[yroot] = xroot + rank[xroot] += 1 + + def kruskal_algo(self): + result = [] + i, e = 0, 0 + self.graph = sorted(self.graph, key=lambda item: item[2]) + parente = [] + rank = [] + for node in range(self.V): + parente.append(node) + rank.append(0) + while e < self.V - 1: + u, v, w = self.graph[i] + i = i + 1 + x = self.find(parente, u) + y = self.find(parente, v) + if x != y: + e = e + 1 + result.append([u, v, w]) + self.apply_union(parente, rank, x, y) + for u, v, weight in result: + print("%d - %d: %d" % (u, v, weight)) + + +g = Graph(6) +g.add_edge(0, 1, 4) +g.add_edge(0, 2, 4) +g.add_edge(1, 2, 2) +g.add_edge(1, 0, 4) +g.add_edge(2, 0, 4) +g.add_edge(2, 1, 2) +g.add_edge(2, 3, 3) +g.add_edge(2, 5, 2) +g.add_edge(2, 4, 4) +g.add_edge(3, 2, 3) +g.add_edge(3, 4, 3) +g.add_edge(4, 2, 4) +g.add_edge(4, 3, 3) +g.add_edge(5, 2, 2) +g.add_edge(5, 4, 3) +g.kruskal_algo() \ No newline at end of file diff --git a/prim.txt b/prim.txt new file mode 100644 index 0000000..9e9a26e --- /dev/null +++ b/prim.txt @@ -0,0 +1,31 @@ +INF = 9999999 +N = 5 +G = [[0, 19, 5, 0, 0], + [19, 0, 5, 9, 2], + [5, 5, 0, 1, 6], + [0, 9, 1, 0, 1], + [0, 2, 6, 1, 0]] + +seceleciona_node = [0, 0, 0, 0, 0] + +no_edge = 0 + +seceleciona_node[0] = True + +print("Edge : Weight\n") +while (no_edge < N - 1): + + minimum = INF + a = 0 + b = 0 + for m in range(N): + if seceleciona_node[m]: + for n in range(N): + if ((not seceleciona_node[n]) and G[m][n]): + if minimum > G[m][n]: + minimum = G[m][n] + a = m + b = n + print(str(a) + "-" + str(b) + ":" + str(G[a][b])) + seceleciona_node[b] = True + no_edge += 1 \ No newline at end of file