def create_event_list(filename):
    """Return a list of Events based on raw list of events in <filename>.

    Precondition: the file stored at <filename> is in the format specified
    by the assignment handout.

    @param filename: str
        The name of a file that contains the list of events.
    @rtype: list[Event]
    """
    events = []
    with open(filename, "r") as file:
        for line in file:
            line = line.strip()

            if not (line or line.startswith("#")):
                continue
            # Skip lines that are blank or start with #.

            # Create a list of words in the line, e.g.
            # Note that these are strings, and you'll need to convert some
            # of them to a different type.
            tokens = line.split()
            timestamp = int(tokens[0])
            event_type = tokens[1]

            # HINT: Use Location.deserialize to convert the location string to
            # a location.

            if event_type == "DriverRequest":
                # TODO
                # Create a DriverRequest event.
                driver_id = tokens[2]
                origin_location = deserialize_location(tokens[3])
                speed = int(tokens[4])
                is_idle = True

                driver = Driver(driver_id, origin_location, speed, is_idle)

                events.append(DriverRequest(timestamp, driver))

            elif event_type == "RiderRequest":
                # TODO
                # Create a RiderRequest event.
                rider_id = tokens[2]
                origin_location = deserialize_location(tokens[3])
                destination_location = deserialize_location(tokens[4])
                paitence = int(tokens[5])
                Status = WAITING

                rider = Rider(rider_id, origin_location, destination_location,
                              Status, paitence)

                event = RiderRequest(timestamp, rider)

                events.append(event)

    return events
Exemplo n.º 2
0
def create_event_list(filename):
    """Return a list of Events based on raw list of events in <filename>.

    Precondition: the file stored at <filename> is in the format specified
    by the assignment handout.

    @param filename: str
        The name of a file that contains the list of events.
    @rtype: list[Event]

    >>> x = create_event_list("events.txt")
    >>> isinstance(x, list)
    True
    """
    events = []
    with open(filename, "r") as file:
        for line in file:
            line = line.strip()

            if not line or line.startswith("#"):
                # Skip lines that are blank or start with #.
                continue

            # Create a list of words in the line, e.g.
            # ['10', 'RiderRequest', 'Cerise', '4,2', '1,5', '15'].
            # Note that these are strings, and you'll need to convert some
            # of them to a different type.
            tokens = line.split()
            timestamp = int(tokens[0])
            event_type = tokens[1]

            id = tokens[2]
            location = deserialize_location(tokens[3])

            # HINT: Use Location.deserialize to convert the location string to
            # a location.

            if event_type == "DriverRequest":
                # TODO
                # Create a DriverRequest event.
                speed = int(tokens[4])

                driver = Driver(id, location, speed)
                event = DriverRequest(timestamp, driver)

            else:
                # TODO
                # Create a RiderRequest event.

                destination = deserialize_location(tokens[4])
                patience = int(tokens[5])

                rider = Rider(id, location, destination, patience)
                event = RiderRequest(timestamp, rider)

            events.append(event)
    return events
Exemplo n.º 3
0
def create_event_list(filename):
    """Return a list of Events based on raw list of events in <filename>.

    Precondition: the file stored at <filename> is in the format specified
    by the assignment handout.

    @param filename: str
        The name of a file that contains the list of events.
    @rtype: list[Event]

    >>> l = create_event_list('events_small.txt')
    >>> len(l)
    2
    >>> [print(event) for event in l]
    1 -- Dan: Request a driver
    10 -- Arnold: Request a rider
    [None, None]
    """
    events = []
    with open(filename, "r") as file:
        for line in file:
            line = line.strip()

            if not line or line.startswith("#"):
                # Skip lines that are blank or start with #.
                continue

            # Create a list of words in the line, e.g.
            # ['10', 'RiderRequest', 'Cerise', '4,2', '1,5', '15'].
            # Note that these are strings, and you'll need to convert some
            # of them to a different type.
            tokens = line.split()
            timestamp = int(tokens[0])
            event_type = tokens[1]

            # HINT: Use Location.deserialize to convert the location string to
            # a location.

            if event_type == "DriverRequest":
                id = tokens[2]
                location = deserialize_location(tokens[3])
                speed = int(tokens[4])
                # Create a DriverRequest event.
                event = DriverRequest(timestamp, Driver(id, location, speed))
            elif event_type == "RiderRequest":
                id = tokens[2]
                origin = deserialize_location(tokens[3])
                destination = deserialize_location(tokens[4])
                patience = int(tokens[5])
                # Create a RiderRequest event.
                event = RiderRequest(timestamp,
                                     Rider(id, origin, destination, patience))

            events.append(event)
    return events
Exemplo n.º 4
0
def create_event_list(filename):
    """Return a list of Events based on raw list of events in <filename>.

    Precondition: the file stored at <filename> is in the format specified
    by the assignment handout.

    @param filename: str
        The name of a file that contains the list of events.
    @rtype: list[Event]

    >>> l = create_event_list('events_small.txt')
    >>> len(l)
    2
    >>> [print(event) for event in l]
    1 -- Dan: Request a driver
    10 -- Arnold: Request a rider
    [None, None]
    """
    events = []
    with open(filename, "r") as file:
        for line in file:
            line = line.strip()

            if not line or line.startswith("#"):
                # Skip lines that are blank or start with #.
                continue

            # Create a list of words in the line, e.g.
            # ['10', 'RiderRequest', 'Cerise', '4,2', '1,5', '15'].
            # Note that these are strings, and you'll need to convert some
            # of them to a different type.
            tokens = line.split()
            timestamp = int(tokens[0])
            event_type = tokens[1]

            # HINT: Use Location.deserialize to convert the location string to
            # a location.

            if event_type == "DriverRequest":
                id = tokens[2]
                location = deserialize_location(tokens[3])
                speed = int(tokens[4])
                # Create a DriverRequest event.
                event = DriverRequest(timestamp, Driver(id, location, speed))
            elif event_type == "RiderRequest":
                id = tokens[2]
                origin = deserialize_location(tokens[3])
                destination = deserialize_location(tokens[4])
                patience = int(tokens[5])
                # Create a RiderRequest event.
                event = RiderRequest(timestamp, Rider(id, origin, destination, patience))

            events.append(event)
    return events
Exemplo n.º 5
0
def create_event_list(filename):
    """Return a list of Events based on raw list of events in <filename>.

    Precondition: the file stored at <filename> is in the format specified
    by the assignment handout.

    @param filename: str
        The name of a file that contains the list of events.
    @rtype: list[Event]
    """
    events = []
    with open(filename, "r") as file:
        for line in file:
            line = line.strip()

            if not line or line.startswith("#"):
                # Skip lines that are blank or start with #.
                continue

            # Create a list of words in the line, e.g.
            # ['10', 'RiderRequest', 'Cerise', '4,2', '1,5', '15'].
            # Note that these are strings, and you'll need to convert some
            # of them to a different type.
            tokens = line.split()
            timestamp = int(tokens[0])
            event_type = tokens[1]

            # HINT: Use Location.deserialize to convert the location string to
            # a location.
            event = []
            if event_type == "DriverRequest":
                # TODO
                # Create a DriverRequest event.

                driverIdentification = tokens[2]
                driverLocation = deserialize_location(tokens[3])
                driverSpeed = int(tokens[4])
                #is that all added to event?
                driver = Driver(driverIdentification,driverLocation,driverSpeed)
                events.append(DriverRequest(timestamp,driver))

            elif event_type == "RiderRequest":
                # TODO
                # Create a RiderRequest event.
                riderIdentification = tokens[2]
                riderLocation= deserialize_location(tokens[3])
                riderDestination = deserialize_location(tokens[4])
                riderPatience = int(tokens[5])
                #is that all added to event?
                rider  = Rider(riderIdentification,WAITING,riderDestination,riderLocation,riderPatience)
                events.append(RiderRequest(timestamp,rider))


    return events
Exemplo n.º 6
0
def create_event_list(filename):
    """Return a list of Events based on raw list of events in <filename>.

    Precondition: the file stored at <filename> is in the format specified
    by the assignment handout.

    @param filename: str
        The name of a file that contains the list of events.
    @rtype: list[Event]
    """

    events = []
    with open(filename, "r") as file:
        for line in file:
            line = line.strip()

            if not line or line.startswith("#"):
                # Skip lines that are blank or start with #.
                continue

            # Create a list of words in the line, e.g.
            # ['10', 'RiderRequest', 'Cerise', '4,2', '1,5', '15'].
            # Note that these are strings, and you'll need to convert some
            # of them to a different type.
            tokens = line.split()
            timestamp = int(tokens[0])
            event_type = tokens[1]

            # HINT: Use Location.deserialize to convert the location string to
            # a location.
            event = None
            if event_type == "DriverRequest":

                # Create a DriverRequest event.
                event = DriverRequest(timestamp, Driver(tokens[2],
                                      deserialize_location(tokens[3]),
                                                        int(tokens[4])))

            elif event_type == "RiderRequest":

                # Create a RiderRequest event.
                event = RiderRequest(timestamp, Rider(tokens[2],
                                     deserialize_location(tokens[3]),
                                     deserialize_location(tokens[4]),
                                                      int(tokens[5])))
            events.append(event)

    return events
Exemplo n.º 7
0
def create_event_list(filename):
    """Return a list of Events based on raw list of events in <filename>.

    Precondition: the file stored at <filename> is in the format specified
    by the assignment handout.

    @param filename: str
        The name of a file that contains the list of events.
    @rtype: list[Event]
    """
    events = []
    with open(filename, "r") as file:
        for line in file:
            line = line.strip()

            if not line or line.startswith("#"):

                # Skip lines that are blank or start with #.
                continue

            # Create a list of words in the line, e.g.
            # ['10', 'RiderRequest', 'Cerise', '4,2', '1,5', '15'].
            # Note that these are strings, and you'll need to convert some
            # of them to a different type.
            tokens = line.split()
            timestamp = int(tokens[0])
            event_type = tokens[1]

            # Append the event when the event is DriverRequest
            if event_type == "DriverRequest":
                identification = tokens[2]
                location = deserialize_location(tokens[3])
                speed = int(tokens[4])
                event = DriverRequest(timestamp,
                                      Driver(identification, location, speed))
                events.append(event)

            # Append the event when the event is RiderRequest
            elif event_type == "RiderRequest":
                identification = tokens[2]
                origin = deserialize_location(tokens[3])
                destination = deserialize_location(tokens[4])
                patience = int(tokens[5])
                event = RiderRequest(
                    timestamp,
                    Rider(identification, origin, destination, patience))
                events.append(event)
    return events
Exemplo n.º 8
0
def create_event_list(filename):
    """Return a list of Events based on raw list of events in <filename>.

    Precondition: the file stored at <filename> is in the format specified
    by the assignment handout.

    @param filename: str
        The name of a file that contains the list of events.
    @rtype: list[Event]
    """
    events = []
    event = None
    with open(filename, "r") as file:
        for line in file:
            line = line.strip()

            if not line or line.startswith("#"):
                # Skip lines that are blank or start with #.
                continue

            # Create a list of words in the line, e.g.
            # ['10', 'RiderRequest', 'Cerise', '4,2', '1,5', '15'].
            # Note that these are strings, and you'll need to convert some
            # of them to a different type.
            tokens = line.split()
            timestamp = int(tokens[0])
            event_type = tokens[1]

            # HINT: Use Location.deserialize to convert the location string to
            # a location.

            if event_type == "DriverRequest":
                driver = Driver(tokens[2], deserialize_location(tokens[3]),
                                int(tokens[4]))
                # Create a DriverRequest event.
                event = DriverRequest(timestamp, driver)
            elif event_type == "RiderRequest":
                rider = Rider(tokens[2], deserialize_location(tokens[3]),
                              deserialize_location(tokens[4]), WAITING,
                              int(tokens[5]))
                # Create a RiderRequest event.
                event = RiderRequest(timestamp, rider)
            if event is not None:
                events.append(event)
    return events
Exemplo n.º 9
0
def create_event_list(filename):
    """Return a list of Events based on raw list of events in <filename>.

    Precondition: the file stored at <filename> is in the format specified
    by the assignment handout.

    @param filename: str
        The name of a file that contains the list of events.
    @rtype: list[Event]
    """

    events = []
    with open(filename, "r") as file:
        for line in file:
            line = line.strip()

            if not line or line.startswith("#"):
                # Skip lines that are blank or start with #.
                continue

            # Create a list of words in the line, e.g.
            # ['10', 'RiderRequest', 'Cerise', '4,2', '1,5', '15'].
            tokens = line.split()
            timestamp = int(tokens[0])
            event_type = tokens[1]

            if event_type == "DriverRequest":
                #Create DriverRequest event.
                driverObject = Driver(tokens[2],
                                      deserialize_location(tokens[3]),
                                      int(tokens[4]))
                event = DriverRequest(timestamp, driverObject)

            elif event_type == "RiderRequest":
                # Create a RiderRequest event.
                riderObject = Rider(tokens[2], deserialize_location(tokens[3]),
                                    deserialize_location(tokens[4]),
                                    int(tokens[5]))
                event = RiderRequest(timestamp, riderObject)

            events.append(event)
    return events
def create_event_list(filename):
"""Return a list of Events based on raw list of events in <filename>.
Precondition: the file stored at <filename> is in the format
specified
by the assignment handout.
@param filename: str
The name of a file that contains the list of events.
@rtype: list[Event]
"""
events = []
with open(filename, "r") as file:
for line in file:
line = line.strip()
if not line or line.startswith("#"):
# Skip lines that are blank or start with #.
continue
# Create a list of words in the line, e.g.
# ['10', 'RiderRequest', 'Cerise', '4,2', '1,5', '15'].
# Note that these are strings, and you'll need to convert
some
# of them to a different type.
tokens = line.split()
timestamp = int(tokens[0])
event_type = tokens[1]
# HINT: Use Location.deserialize to convert the location
string to
# a location.
if event_type == "DriverRequest":
# Create a DriverRequest event.
driver = Driver(tokens[2],
deserialize_location(tokens[3]),
int(tokens[4]))
event = DriverRequest(timestamp, driver)
events.append(event)
elif event_type == "RiderRequest":
# Create a RiderRequest event.
rider = Rider(tokens[2], deserialize_location(tokens[3]),
deserialize_location(tokens[4]),
int(tokens[5]))
event = RiderRequest(timestamp, rider)
events.append(event)
return events
# Sample Event List
# The parser will skip empty lines, lines with whitespace only,
# or those that start with '#'.
# The format for DriverRequest events is:
# <timestamp> DriverRequest <driver id> <location> <speed>
# <location> is <row>,<col>
0 DriverRequest Amaranth 1,1 1
0 DriverRequest Bergamot 1,2 1
0 DriverRequest Crocus 3,1 1
0 DriverRequest Dahlia 3,2 1
0 DriverRequest Edelweiss 4,2 1
0 DriverRequest Foxglove 5,2 1
# The format for RiderRequest events is:
# <timestamp> RiderRequest <rider id> <origin> <destination> <patience>
# <origin>, <destination> are <row>,<col>
0 RiderRequest Almond 1,1 5,5 10
5 RiderRequest Bisque 3,2 2,3 5
10 RiderRequest Cerise 4,2 1,5 15
15 RiderRequest Desert 5,1 4,3 5
20 RiderRequest Eggshell 3,4 3,1 1
25 RiderRequest Fallow 2,1 2,5 10
#At time 1, Dan exists
#Dan is at location 1,1, requests a driver, and is willing
#to wait 15 units of time for pickup before he cancels
1 RiderRequest Dan 1,1 6,6 15
#At time 10, Arnold exists
#Arnold is at location 3,3, requests a rider,
#and Arnold's car moves 2 units of distance per unit time
10 DriverRequest Arnold 3,3 2
class Location:
"""
Our simulation plays out on a simplified grid of city blocks.
Each location is specified by a pair of (row, column)
Attribute:
==========
@type row: non-negative integer
number of blocks from the bottom
@type column: non-negative integer
number of blocks from the left
"""
def __init__(self, row, column):
"""Initialize a location.
@type self: Location
@type row: int
@type column: int
@rtype: None
"""
self.row = row
self.column = column
def __str__(self):
"""Return a string representation.
@type self: Location
@rtype: str
>>> l = Location (2,3)
>>> print(l)
2,3
"""
return "{},{}".format(self.row, self.column)
def __eq__(self, other):
"""Return True if self equals other, and false otherwise.
@type self:Location
@type other: Location | Any
@rtype: bool
>>> l1 = Location (3,4)
>>> l2 = Location (3, 4)
>>> l3 = Location (5,6)
>>> l1 == l2
True
>>> l1 == l3
False
"""
return (type(self) == type(other) and
self.column == other.column and
self.row == other.row)
def manhattan_distance(origin, destination):
"""Return the Manhattan distance between the origin and the
destination.
@type origin: Location
@type destination: Location
@rtype: int
>>> manhattan_distance(Location(2,3),Location(5,7))
7
>>> manhattan_distance(Location(2,3),Location(2,7))
4
"""
return (abs(origin.column - destination.column) +
abs(origin.row - destination.row))
def deserialize_location(location_str):
"""Deserialize a location.
@type location_str: str
A location in the format 'row,col'
@rtype: Location
>>> d1 = deserialize_location('24,35')
>>> print (d1)
24,35
>>> d2 = deserialize_location('6,4')
>>> print(d2)
6,4
"""
l = Location(0, 0)
index_comma = location_str.find(',')
l.row = int(location_str[:index_comma])
l.column = int(location_str[index_comma+1:])
return l
if __name__ == "__main__":
import doctest
doctest.testmod()
from location import Location
from location import manhattan_distance
"""
The Monitor module contains the Monitor class, the Activity class,
and a collection of constants. Together the elements of the module
help keep a record of activities that have occurred.
Activities fall into two categories: Rider activities and Driver
activities. Each activity also has a description, which is one of
request, cancel, pickup, or dropoff.
=== Constants ===
@type RIDER: str
A constant used for the Rider activity category.
@type DRIVER: str
A constant used for the Driver activity category.
@type REQUEST: str
A constant used for the request activity description.
@type CANCEL: str
A constant used for the cancel activity description.
@type PICKUP: str
A constant used for the pickup activity description.
@type DROPOFF: str
A constant used for the dropoff activity description.
"""
RIDER = "rider"
DRIVER = "driver"
REQUEST = "request"
CANCEL = "cancel"
PICKUP = "pickup"
DROPOFF = "dropoff"
class Activity:
"""An activity that occurs in the simulation.
=== Attributes ===
@type timestamp: int
The time at which the activity occurred.
@type description: str
A description of the activity.
@type identifier: str
An identifier for the person doing the activity.
@type location: Location
The location at which the activity occurred.
"""
def __init__(self, timestamp, description, identifier, location):
"""Initialize an Activity.
@type self: Activity
@type timestamp: int
@type description: str
@type identifier: str
@type location: Location
@rtype: None
"""
self.description = description
self.time = timestamp
self.id = identifier
self.location = location
class Monitor:
"""A monitor keeps a record of activities that it is notified about.
When required, it generates a report of the activities it has
recorded.
"""
# === Private Attributes ===
# @type _activities: dict[str, dict[str, list[Activity]]]
# A dictionary whose key is a category, and value is another
# dictionary. The key of the second dictionary is an identifier
# and its value is a list of Activities.
def __init__(self):
"""Initialize a Monitor.
@type self: Monitor
"""
self._activities = {
RIDER: {},
DRIVER: {}
}
"""@type _activities: dict[str, dict[str, list[Activity]]]"""
def __str__(self):
"""Return a string representation.
@type self: Monitor
@rtype: str
>>> m = Monitor()
>>> A1 = Activity(1,"request","Chris",Location(0,0))
>>> A2 = Activity(3,"pickup","Chris",Location(10,2))
>>> A3 = Activity(5,"request","Jack",Location(1,3))
>>> A4 = Activity(6,"pickup","Louis",Location(6,7))
>>> A5 = Activity(2,"request","Chen",Location(3,3))
>>> A6 = Activity(6,"cancel","Chen",Location(3,3))
>>> A7 = Activity(10,"pickup","LK",Location(0,0))
>>> m._activities = {RIDER:{"Chen":[A5,A6],"Jack":[A3]},\
DRIVER:{"Chris":[A1,A2],"Louis":[A4],"LK":[A7]}}
>>> print(m)
Monitor (3 drivers, 2 riders)
"""
return "Monitor ({} drivers, {} riders)".format(
len(self._activities[DRIVER]),
len(self._activities[RIDER]))
def notify(self, timestamp, category, description, identifier,
location):
"""Notify the monitor of the activity.
@type self: Monitor
@type timestamp: int
The time of the activity.
@type category: DRIVER | RIDER
The category for the activity.
@type description: REQUEST | CANCEL | PICKUP | DROP_OFF
A description of the activity.
@type identifier: str
The identifier for the actor.
@type location: Location
The location of the activity.
@rtype: None
"""
if identifier not in self._activities[category]:
self._activities[category][identifier] = []
activity = Activity(timestamp, description, identifier, location)
self._activities[category][identifier].append(activity)
def report(self):
"""Return a report of the activities that have occurred.
@type self: Monitor
@rtype: dict[str, object]
"""
return {"rider_wait_time": self._average_wait_time(),
"driver_total_distance": self._average_total_distance(),
"driver_ride_distance": self._average_ride_distance()}
def _average_wait_time(self):
"""Return the average wait time of riders that have either been
picked
up or have cancelled their ride.
@type self: Monitor
@rtype: float
>>> m1 = Monitor()
>>> A1 = Activity(1,"request","Chris",Location(0,0))
>>> A2 = Activity(3,"pickup","Chris",Location(10,2))
>>> A3 = Activity(5,"request","Jack",Location(1,3))
>>> A4 = Activity(6,"request","Louis",Location(6,7))
>>> A5 = Activity(2,"request","Chen",Location(3,3))
>>> A6 = Activity(6,"cancel","Chen",Location(3,3))
>>> A7 = Activity(9,"pickup","Louis",Location(0,0))
>>> m1._activities = {RIDER:{"Chris":[A1,A2],"Jack":[A3],\
"Louis":[A4,A7],"Chen":[A5,A6]},DRIVER:{}}
>>> m1.average_wait_time()
3.0
"""
wait_time = 0
count = 0
for activities in self._activities[RIDER].values():
# A rider that has less than two activities hasn't finished
# waiting (they haven't cancelled or been picked up).
if len(activities) >= 2:
# The first activity is REQUEST, and the second is PICKUP
# or CANCEL. The wait time is the difference between the
two.
wait_time += activities[1].time - activities[0].time
count += 1
return wait_time / count
@property
def average_wait_time(self):
return self._average_wait_time()
def _average_total_distance(self):
"""Return the average distance drivers have driven.
@type self: Monitor
@rtype: float
>>> m2 = Monitor()
>>> A1 = Activity(1,"request","Chris",Location(0,0))
>>> A2 = Activity(3,"pickup","Chris",Location(10,2))
>>> A3 = Activity(5,"dropoff","Chris",Location(1,3))
>>> A4 = Activity(6,"request","Louis",Location(6,7))
>>> A5 = Activity(2,"request","Chen",Location(3,3))
>>> A6 = Activity(6,"cancel","Chen",Location(4,3))
>>> A7 = Activity(9,"cancel","Louis",Location(0,0))
>>> m2._activities = {RIDER:{},DRIVER:{"Chris":[A1,A2,A3],\
"Louis":[A4,A7],"Chen":[A5,A6]}}
>>> m2.average_total_distance()
12.0
"""
total_distance = 0
num_drivers = len(self._activities[DRIVER])
for activities in self._activities[DRIVER].values():
i = 1
while i < len(activities):
total_distance +=
manhattan_distance(activities[i].location,
activities[i-
1].location)
i += 1
return total_distance / num_drivers
@property
def average_total_distance(self):
return self._average_total_distance()
def _average_ride_distance(self):
"""Return the average distance drivers have driven on rides.
@type self: Monitor
@rtype: float
>>> m3 = Monitor()
>>> A1 = Activity(1,"request","Chris",Location(0,0))
>>> A2 = Activity(3,"pickup","Chris",Location(10,2))
>>> A3 = Activity(5,"dropoff","Chris",Location(1,3))
>>> A4 = Activity(6,"request","Louis",Location(6,7))
>>> A5 = Activity(2,"request","Chen",Location(3,3))
>>> A6 = Activity(6,"pickup","Chen",Location(4,0))
>>> A7 = Activity(10,"dropoff","Chen",Location(13,20))
>>> A8 = Activity(9,"cancel","Louis",Location(0,0))
>>> m3._activities = {RIDER:{},DRIVER:{"Chris":[A1,A2,A3],\
"Louis":[A4,A8],"Chen":[A5,A6,A7]}}
>>> m3.average_ride_distance()
13.0
"""
ride_distance = 0
num_drivers = len(self._activities[DRIVER])
for activities in self._activities[DRIVER].values():
for activity in activities:
if activity.description == PICKUP:
i = activities.index(activity)
ride_distance += manhattan_distance(
activities[i + 1].location,
activities[i].location)
return ride_distance / num_drivers
@property
def average_ride_distance(self):
return self._average_ride_distance()
from location import Location
"""
The rider module contains the Rider class. It also contains
constants that represent the status of the rider.
=== Constants ===
@type WAITING: str
A constant used for the waiting rider status.
@type CANCELLED: str
A constant used for the cancelled rider status.
@type SATISFIED: str
A constant used for the satisfied rider status
"""
WAITING = "waiting"
CANCELLED = "cancelled"
SATISFIED = "satisfied"
class Rider:
"""A rider for a ride-sharing service.
=== Attributes ===
@type id: str
A unique identifier for the rider.
@type origin: Location
The starting location
@type destination: Location
The ending location
@type status: str
WAITING, CANCELLED or SATISFIED
@type patience: int
The number of time units the rider will wait to be picked up before
they
cancel their ride
"""
def __init__(self, identifier, origin, destination, patience):
"""Initialize a Driver.
@type self:Rider
@type identifier: str
@type origin: Location
@type destination: Location
@type patience: int
@rtype: None
"""
self.id = identifier
self.origin = origin
self.destination = destination
self.patience = patience
self.status = WAITING
def __str__(self):
"""Return a string representation.
@type self: Rider
@rtype: str
>>> r = Rider("Alex",Location(1,2),Location(3,4), 12)
>>> print(r)
Alex 1,2 3,4 12
"""
return "{} {} {} {}".format(self.id, self.origin,
self.destination,
self.patience)
def __eq__(self, other):
"""Return True if self equals other, and false otherwise.
@type self: Rider
@type other: Rider | Any
@rtype:bool
>>> r1 = Rider("Alex",Location(1,2),Location(3,4), 10)
>>> r2 = Rider("Alex",Location(1,2),Location(3,4),10)
>>> r3 = Rider("Shawn",Location(3,2),Location(2,4), 15)
>>> r1 == r2
True
>>> r1 == r3
False
"""
return (type(self) == type(other) and
self.id == other.id and
self.origin == other.origin and
self.destination == other.destination and
self.patience == other.patience)
if __name__ == "__main__":
import doctest
doctest.testmod()
from container import PriorityQueue
from dispatcher import Dispatcher
from event import create_event_list
from monitor import Monitor
class Simulation:
"""A simulation.
This is the class which is responsible for setting up and running a
simulation.
The API is given to you: your main task is to implement the run
method below according to its docstring.
Of course, you may add whatever private attributes and methods you
want.
But because you should not change the interface, you may not add any
public
attributes or methods.
This is the entry point into your program, and in particular is used
for
auto-testing purposes. This makes it ESSENTIAL that you do not change
the
interface in any way!
"""
# === Private Attributes ===
# @type _events: PriorityQueue[Event]
# A sequence of events arranged in priority determined by the
event
# sorting order.
# @type _dispatcher: Dispatcher
# The dispatcher associated with the simulation.
def __init__(self):
"""Initialize a Simulation.
@type self: Simulation
@rtype: None
"""
self._events = PriorityQueue()
self._dispatcher = Dispatcher()
self._monitor = Monitor()
def run(self, initial_events):
"""Run the simulation on the list of events in <initial_events>.
Return a dictionary containing statistics of the simulation,
according to the specifications in the assignment handout.
@type self: Simulation
@type initial_events: list[Event]
An initial list of events.
@rtype: dict[str, object]
"""
# Add all initial events to the event queue.
for event in initial_events:
self._events.add(event)
while self._events.is_empty() is False:
executed_event = self._events.remove()
result_events = executed_event.do(self._dispatcher,
self._monitor)
# this warning can be ignored
if result_events is not None:
for result_event in result_events:
self._events.add(result_event)
# Until there are no more events, remove an event
# from the event queue and do it. Add any returned
# events to the event queue.
return self._monitor.report()
if __name__ == "__main__":
events = create_event_list("events.txt")
sim = Simulation()
final_stats = sim.run(events)
print(final_stats)