Related
I am working through a book on algorithms and it contains a description of Dijkstra's algorithm with a code sample in Ruby. The code solves a hypothetical problem of finding the cheapest flight path from city A to city B. You cannot necessarily fly directly from A to B, and so there may be multiple flights required to complete your trip.
A City object has a #name that is a String and #routes that is a hash with a City object as the key and ticket price as the value.
For example, the city of Atlanta is defined by
atlanta = City.new("Atlanta")
atlanta.add_route(boston, 100)
atlanta.add_route(denver, 160)
# where the add_route method states that
#routes[city] = price
Further, unvisited_cities is an array of City objects, and cheapest_prices_table is a hash with a city #name as the key and ticket price as the value.
My question is, what does the following code, which is part of the Dijkstra algorithm code sample, do? I am unfamiliar with the syntax unvisited_cities.min do |city|. I placed a puts statement just above the code in question (p unvisited_cities.min), and I received an error: ArgumentError (comparison of City with City failed). I could not find a description of this syntax anywhere to understand exactly what the lines below do. That is, how does the code below set current_city to be the least expensive city to fly to in unvisited_cities?
# We visit our next unvisited city. We choose the one that is cheapest
# to get to from the STARTING city:
current_city = unvisited_cities.min do |city|
cheapest_prices_table[city.name]
end
Thank you!
I'm using the online compiler https://swish.swi-prolog.org/
Given the next facts:
frontier(spain,france).
frontier(spain,portugal).
frontier(portugal,spain).
frontier(france,spain).
frontier(france,italy).
frontier(france,germany).
frontier(france,belgium).
frontier(france,swiztland).
frontier(belgium,netherlands).
frontier(belgium,france).
frontier(belgium,germany).
frontier(netherlands,germany).
frontier(netherlands,belgium).
frontier(germany,netherlands).
frontier(germany,belgium).
frontier(germany,france).
frontier(germany,austria).
frontier(germany,swiztland).
frontier(austria,germany).
frontier(austria,swiztland).
frontier(austria,italy).
frontier(swiztland,austria).
frontier(swiztland,france).
frontier(swiztland,germany).
frontier(swiztland,italy).
frontier(italy,france).
frontier(italy,swiztland).
frontier(italy,austria).
I would like to obtain all of the countries but without obtain repeated ones.
Thus, I use a setof predicate, which avoids the repeated, like this:
setof(Country, (frontier(Country,_)), Countries).
The problem is that, when I executed the query, I obtained some iterations:
[germany, italy, swiztland]
[france, germany, netherlands]
[belgium, germany, italy, spain, swiztland],
[austria, belgium, france, netherlands, swiztland]
[austria, france, swiztland]
[belgium, germany]
[spain]
[france, portugal]
[austria, france, germany, italy]
I don't understand why, I was expected that the list Countries return me the list of all the countries without repeated ones and sorted, that's why I use the anonymus variable in the second argument of the predicate frontier, because I don't care about the second argument, only I want the first argument without repeated ones.
Any help?
I have a list of facts that have those parameters: Name, Longitude, Latitude. I want to write a predicate that sorts the Latitude only.
Here's part of my facts.
pool(roy, -75.702744, 45.4089761).
pool(marth, -75.731638, 45.3803301).
pool(jiggy, -75.7449645, 45.40431589).
pool(yamaha, -75.7114829, 45.3993461).
I tried to do something of the following but didn't get lucky:
furthest(Lat-Long):- setof(Lat-Long, pool(_, Long, Lat), [Lat-Long|_]).
Any ideas of how I should tackle this?
does this work?
pool(roy, -75.702744, 45.4089761).
pool(marth, -75.731638, 45.3803301).
pool(jiggy, -75.7449645, 45.40431589).
pool(yamaha, -75.7114829, 45.3993461).
my_sort:-
findall(forsort(Lat,Name),pool(Name,Long,Lat),List),
msort(List,Sorted),
write(Sorted).
?- my_sort.
[forsort(45.3803301,marth),forsort(45.3993461,yamaha),forsort(45.40431589,jiggy),forsort(45.4089761,roy)]
true.
Excerpt of manual below(SWI):
msort sorts List to the standard order of terms
Standard Order of Terms:
Compound terms are first checked on their arity, then on their functor name (alphabetically) and
finally recursively on their arguments, leftmost argument first.
% A quiz team structure takes the form:
% team(Captain, Vice_captain, Regular_team_members).
% Captain and Vice_captain are player structures;
% Regular_team_members is a list of player structures.
% player structures take the form:
% player(First_name, Surname, details(Speciality,Recent_score)).
team(player(niall,elliott,details(history,11)),
player(michelle,cartwright,details(fashion,19)),
[player(peter,lawlor,details(science,12)),
player(louise,boyle,details(current_affairs,17))]).
I've been given the database above (I haven't copied over all the entries of people as it would be too long).
I've been asked to get the surname of any vice-captain whose team includes a captain or a regular team member whose speciality is science.
I can get the surname of the vice-captains using the code below but I can't return only those teams that include a captain or regular team members whose speciality is science. What would I need to add to do this?
part_two(Surname):-
team(_,player(_,Surname,_),_).
I've also been asked to also get the first name and the surname of any captain whose regular team members number more than one and who all have the same surnames.
This is my attempt so far:
part_three(First_name,Surname):-
team(Captain,_,Regular_team_members),
first_name(Captain,First_name),
surname(Captain,Surname),
Regular_team_members=[_,_|_].
I just need to exclude the details of those captains whose regular team members don't all have the same surname.
part_two(Surname):-
team(Captain, Vice_captain, Regular_team_members),
surname(Vice_captain, Surname),
member(Player, [Captain|Regular_team_members]),
specialty(Player, science).
% 'abstract data structures' accessors
surname(player(_First_name, Surname, _Details), Surname).
specialty(player(_First_name, _Surname, details(Speciality, _Recent_score)), Speciality).
Since you're going anyway to scan the Regular_team_members list, looking for appropriate constraint, you can get a simpler 'program' first 'joining' the Captain to other players.
You could change a little what you have already written as follows:
part_two(Surname):-
team(P,player(_,Surname,_),L),
( P=player(_,_,details(science,_)) -> true ; member(player(_,_,details(science,_)),L) ).
Example:
Database:
team(player(niall,elliott,details(history,11)),
player(michelle,cartwright,details(fashion,19)),
[player(peter,lawlor,details(history,12)),
player(louise,boyle,details(current_affairs,17))]).
team(player(niall1,elliott1,details(science,11)),
player(michelle1,cartwright1,details(fashion,19)),
[player(peter,lawlor,details(history,12)),
player(louise,boyle,details(current_affairs,17))]).
team(player(niall2,elliott2,details(history,11)),
player(michelle2,cartwright2,details(fashion,19)),
[player(peter,lawlor,details(science,12)),
player(louise,boyle,details(current_affairs,17))]).
team(player(niall3,elliott3,details(science,11)),
player(michelle3,cartwright3,details(fashion,19)),
[player(peter,lawlor,details(science,12)),
player(louise,boyle,details(current_affairs,17))]).
Now querying:
?- part_two(X).
X = cartwright1 ;
X = cartwright2 ;
X = cartwright3.
after fiddling around with dictionaries, I came to the conclusion, that I would need a data structure that would allow me an n to n lookup. One example would be: A course can be visited by several students and each student can visit several courses.
What would be the most pythonic way to achieve this? It wont be more than 500 Students and 100 courses, to stay with the example. So I would like to avoid using a real database software.
Thanks!
Since your working set is small, I don't think it is a problem to just store the student IDs as lists in the Course class. Finding students in a class would be as simple as doing
course.studentIDs
To find courses a student is in, just iterate over the courses and find the ID:
studentIDToGet = "johnsmith001"
studentsCourses = list()
for course in courses:
if studentIDToGet in course.studentIDs:
studentsCourses.append(course.id)
There's other ways you could do it. You could have a dictionary of studentIDs mapped to courseIDs or two dictionaries that - one mapped studentIDs:courseIDs and another courseIDs:studentIDs - when updated, update each other.
The implementation I wrote out the code for would probably be the slowest, which is why I mentioned that your working set is small enough that it would not be a problem. The other implentations I mentioned but did not show the code for would require some more code to make them work that just aren't worth the effort.
It depends completely on what operations you want the structure to be able to carry out quickly.
If you want to be able to quickly look up properties related to both a course and a student, for example how many hours a student has spent on studies for a specific course, or what grade the student has in the course if he has finished it, and if he has finished it etc. a vector containing n*m elements is probably what you need, where n is the number of students and m is the number of courses.
If on the other hand the average number of courses a student has taken is much less than the total number of courses (which it probably is for a real case scenario), and you want to be able to quickly look up all the courses a student has taken, you probably want to use an array consisting of n lists, either linked lists, resizable vectors or similar – depending on if you want to be able to with the lists; maybe that is to quickly remove elements in the middle of the lists, or quickly access an element at a random location. If you both want to be able to quickly remove elements in the middle of the lists and have quick random access to list elements, then maybe some kind of tree structure would be the most suitable for you.
Most tree data structures carry out all basic operations in logarithmic time to the number of elements in the tree. Beware that some tree data structures have an amortized time on these operators that is linear to the number of elements in the tree, even though the average time for a randomly constructed tree would be logarithmic. A typical example of when this happens is if you use a binary search tree and build it up with increasingly large elements. Don't do that; scramble the elements before you use them to build up the tree in that case, or use a divide-and-conquer method and split the list in two parts and one pivot element and create the tree root with the pivot element, then recursively create trees from both the left part of the list and the right part of the list, these also using the divide-and-conquer method, and attach them to the root as the left child and the right child respectively.
I'm sorry, I don't know python so I don't know what data structures that are part of the language and which you have to create yourself.
I assume you want to index both the Students and Courses. Otherwise you can easily make a list of tuples to store all Student,Course combinations: [ (St1, Crs1), (St1, Crs2) .. (St2, Crs1) ... (Sti, Crsi) ... ] and then do a linear lookup everytime you need to. For upto 500 students this ain't bad either.
However if you'd like to have a quick lookup either way, there is no builtin data structure. You can simple use two dictionaries:
courses = { crs1: [ st1, st2, st3 ], crs2: [ st_i, st_j, st_k] ... }
students = { st1: [ crs1, crs2, crs3 ], st2: [ crs_i, crs_j, crs_k] ... }
For a given student s, looking up courses is now students[s]; and for a given course c, looking up students is courses[c].
For something simple like what you want to do, you could create a simple class with data members and methods to maintain them and keep them consistent with each other. For this problem two dictionaries would be needed. One keyed by student name (or id) that keeps track of the courses each is taking, and another that keeps track of which students are in each class.
defaultdicts from the 'collections' module could be used instead of plain dicts to make things more convenient. Here's what I mean:
from collections import defaultdict
class Enrollment(object):
def __init__(self):
self.students = defaultdict(set)
self.courses = defaultdict(set)
def clear(self):
self.students.clear()
self.courses.clear()
def enroll(self, student, course):
if student not in self.courses[course]:
self.students[student].add(course)
self.courses[course].add(student)
def drop(self, course, student):
if student in self.courses[course]:
self.students[student].remove(course)
self.courses[course].remove(student)
# remove student if they are not taking any other courses
if len(self.students[student]) == 0:
del self.students[student]
def display_course_enrollments(self):
print "Class Enrollments:"
for course in self.courses:
print ' course:', course,
print ' ', [student for student in self.courses[course]]
def display_student_enrollments(self):
print "Student Enrollments:"
for student in self.students:
print ' student', student,
print ' ', [course for course in self.students[student]]
if __name__=='__main__':
school = Enrollment()
school.enroll('john smith', 'biology 101')
school.enroll('mary brown', 'biology 101')
school.enroll('bob jones', 'calculus 202')
school.display_course_enrollments()
print
school.display_student_enrollments()
school.drop('biology 101', 'mary brown')
print
print 'After mary brown drops biology 101:'
print
school.display_course_enrollments()
print
school.display_student_enrollments()
Which when run produces the following output:
Class Enrollments:
course: calculus 202 ['bob jones']
course: biology 101 ['mary brown', 'john smith']
Student Enrollments:
student bob jones ['calculus 202']
student mary brown ['biology 101']
student john smith ['biology 101']
After mary brown drops biology 101:
Class Enrollments:
course: calculus 202 ['bob jones']
course: biology 101 ['john smith']
Student Enrollments:
student bob jones ['calculus 202']
student john smith ['biology 101']