scientific-programming-exer.../exam/ex01/connectivity.py

32 lines
940 B
Python
Raw Normal View History

from collections import deque
2019-02-15 10:47:50 +00:00
from cfg import config
2019-02-19 13:16:22 +00:00
from db_util import get_page_id
2019-02-15 10:47:50 +00:00
def can_reach(title, connection):
2019-02-19 13:16:22 +00:00
page = get_page_id(title, connection)
cursor = connection.cursor()
2019-02-19 13:16:22 +00:00
cursor.execute("SELECT COUNT(destination) FROM links WHERE destination=%s", (page, ))
count = cursor.fetchone()[0]
return count > 0
def shortest_path(center, title, connection):
if(not can_reach(title, connection)):
return []
cursor = connection.cursor()
2019-02-19 13:16:22 +00:00
current_page = get_page_id(title, connection)
center_page = get_page_id(center, connection)
path = deque()
2019-02-19 13:16:22 +00:00
while(current_page != center_page):
path.append(current_title)
2019-02-15 11:46:32 +00:00
cursor.execute('''SELECT links.source
FROM links
2019-02-19 13:16:22 +00:00
LEFT JOIN dijkstra_helper ON links.destination=dijkstra_helper.page
WHERE links.destination=:page
2019-02-15 11:46:32 +00:00
ORDER BY dijkstra_helper.value ASC
2019-02-19 13:16:22 +00:00
LIMIT 1''', {"page": current_page})
current_title = cursor.fetchone()[0]
return list(reversed(path))