Guest User

Untitled

a guest
Apr 20th, 2021
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.41 KB | None | 0 0
  1. # ==================== #
  2. # Nome: Tiago Madeira #
  3. # Nº de Aluno: 95088 #
  4. # UC: EDA #
  5. # Trabalho 6 #
  6. # ==================== #
  7.  
  8. ''' Modules '''
  9. from csv import reader
  10. import matplotlib.pyplot as plt
  11.  
  12.  
  13. ''' === Exercício 2 === '''
  14.  
  15. ''' alínea a) - Crie uma subclasse Station, para conter o id da estação e a posição, em graus decimais, da
  16. localização do objeto à superfície da terra '''
  17. class Station:
  18.  
  19. __slots__ = "_id_station", "_position"
  20.  
  21. def __init__(self, id_station, position):
  22. self._id_station = id_station # id da estação
  23. self._position = position # posição
  24.  
  25. # retorna o id da station
  26. @property
  27. def id_station(self):
  28. return self._id_station
  29.  
  30. # retorna a posição da station
  31. @property
  32. def position(self):
  33. return self._position
  34.  
  35. def __str__(self):
  36. return f"Station: {self._id_station}, {self._position}"
  37.  
  38. '''Comparação de vértices'''
  39. def __eq__(self, other):
  40. if isinstance(other, Station):
  41. return self._id_station == other.id_station
  42. return False
  43.  
  44. '''Unicidade do elemento'''
  45. def __hash__(self):
  46. '''Referência de memória (usada por causa das keys dos dicionários)'''
  47. return hash(id(self)) # agarra num objeto e transforma num código único
  48.  
  49. ''' alínea b) - Crie uma lista de objetos Station a partir do conjunto de dados em lisbon.stations.csv '''
  50. def read_stations(self):
  51. f = open("lisbon.stations.csv", "r") # lê o ficheiro lisbon.stations.csv
  52. for line in f:
  53. line_clean = line.strip() # Remove espaços que estejam no início e no fim de cada linha
  54. lst = line_clean.split(",") # cria uma lista com cada item da linha, sendo que o delimiter é a ","
  55. print(lst)
  56. f.close()
  57.  
  58. ''' alínea c) - Em Edge, crie uma subclasse Edge_line, para conter a linha de que a conexão faz parte '''
  59. class Edge_line:
  60. __slots__ = "_origem", "_destino", "_linha", "_stations_lines"
  61.  
  62. def __init__(self, origem, destino, linha=None):
  63. self._origem = origem
  64. self._destino = destino
  65. self._linha = linha
  66. self._stations_lines = []
  67. with open('lisbon.lines.csv', 'r') as input_file: # lê o ficheiro lisbon.lines.csv
  68. station_line = reader(input_file, delimiter=',')
  69. next(station_line)
  70. for row in station_line:
  71. print(row)
  72.  
  73. @property
  74. def origem(self):
  75. return self._origem
  76.  
  77. @property
  78. def destino(self):
  79. return self._destino
  80.  
  81. @property
  82. def linha(self):
  83. return self._linha
  84.  
  85. def endpoints(self):
  86. return self._origem, self._destino
  87.  
  88. def opposite(self, v):
  89. '''return self._destino if v is self._origem else self._origem'''
  90. if v is self._origem: # verifica a instância
  91. return self._destino
  92. else:
  93. return self._origem
  94.  
  95. def __eq__(self, other):
  96. """compara element"""
  97. if isinstance(other, Edge):
  98. return self._origem == other._origem and self._destino == other._destino and self._peso == other._peso
  99. return False
  100.  
  101. def __str__(self):
  102. return f"Edge: ({self._origem}, {self._destino})"
  103.  
  104. def __hash__(self):
  105. return hash((id(self._origem), id(self._destino))) # permite obter a referência de memória do objeto
  106.  
  107. def read_connections(self):
  108. f = open("lisbon.connections.csv", "r") # lê o ficheiro lisbon.connections.csv
  109. for line in f:
  110. line_clean = line.strip() # Remove espaços que estejam no início e no fim de cada linha
  111. lst = line_clean.split(",") # cria uma lista com cada item da linha, sendo que o delimiter é a ","
  112. print(lst)
  113. f.close()
  114.  
  115. def read_lines(self):
  116. f = open("lisbon.lines.csv", "r") # lê o ficheiro lisbon.lines.csv
  117. for line in f:
  118. line_clean = line.strip() # Remove espaços que estejam no início e no fim de cada linha
  119. lst = line_clean.split(",") # cria uma lista com cada item da linha, sendo que o delimiter é a ","
  120. print(lst)
  121. f.close()
  122.  
  123. ''' alínea e) - Crie uma estrutura de Grafo, i.e., utilize uma das classes do exercício 3) do Módulo 7 '''
  124. class GraphList:
  125.  
  126. def __init__(self, directed=False): # não dirigido
  127. self._outgoing = {} # de onde se parte
  128. self._incoming = {} if directed else self._outgoing # quando não tem direção o incoming é o mesmo dicionário que o outgoing
  129.  
  130. def is_directed(self):
  131. return self._outgoing is not self._incoming # se é dirigido
  132.  
  133. def vertex_count(self):
  134. return len(self._outgoing)
  135.  
  136. def vertices(self):
  137. return self._outgoing.keys()
  138.  
  139. def edge_count(self):
  140. # total = sum(len(self._outgoing[key]) for key in self._outgoing)
  141. total = 0
  142. for key in self._outgoing:
  143. value = self._outgoing[key]
  144. total += len(value)
  145. return total if self.is_directed() else total // 2
  146.  
  147. def edges(self):
  148. result = set()
  149. for list_edges in self._outgoing.values():
  150. for e in list_edges:
  151. result.add(e)
  152. # result.update(list_edges) # união
  153. return result
  154.  
  155. def get_edge(self, u, v):
  156. edge = Edge(u, v)
  157. for e in self._outgoing[u]:
  158. if e == edge:
  159. return e
  160. return None
  161.  
  162. def degree(self, v, outgoing=True):
  163. adj = self._outgoing if outgoing else self._incoming
  164. return len(adj[v])
  165.  
  166. def insert_vertex(self, v):
  167. self._outgoing[v] = ListaL()
  168. if self.is_directed():
  169. self._incoming[v] = ListaL()
  170.  
  171. def insert_edge(self, a):
  172. '''TAD exercícios'''
  173. self._outgoing[a.origem].add(a)
  174. self._incoming[a.destino].add(a)
  175.  
  176. def remove_edge(self, edge):
  177. for e in self._outgoing[edge.origem]:
  178. o, d = e.endpoints()
  179. if o == edge.origem and d == edge.destino:
  180. self._outgoing[edge.origem].remove(e)
  181. self._outgoing[edge.destino].remove(e)
  182.  
  183. ''' alínea f) - Crie um procedimento/método para poder visualizar a rede. '''
  184. #fig = plt.figure()
  185. #plt.line(x,y,c=cor)
  186.  
  187.  
  188. if __name__ == '__main__':
  189. s = Station(1, 3.14)
  190. e = Edge_line(1, 2, 1)
Advertisement
Add Comment
Please, Sign In to add comment