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

32 lines
940 B
Python

from collections import deque
from cfg import config
from db_util import get_page_id
def can_reach(title, connection):
page = get_page_id(title, connection)
cursor = connection.cursor()
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()
current_page = get_page_id(title, connection)
center_page = get_page_id(center, connection)
path = deque()
while(current_page != center_page):
path.append(current_title)
cursor.execute('''SELECT links.source
FROM links
LEFT JOIN dijkstra_helper ON links.destination=dijkstra_helper.page
WHERE links.destination=:page
ORDER BY dijkstra_helper.value ASC
LIMIT 1''', {"page": current_page})
current_title = cursor.fetchone()[0]
return list(reversed(path))