forked from futurulus/falcon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
schedule.py
88 lines (74 loc) · 2.64 KB
/
schedule.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import bisect
import flight
class Schedule:
def __init__(self, *args, **kwargs):
self.flights = []
if len(args) == 1:
self.load_file(args[0])
elif len(args) == 0:
if 'filename' in kwargs:
self.load_file(kwargs['filename'])
elif kwargs:
raise TypeError('Schedule constructor got an unexpected ' \
'keyword argument \'%s\'' % kwargs.keys()[0])
else:
self.filename = None
else:
raise TypeError('Schedule constructor takes 0 or 1 positional ' \
'argument (%d given)' % len(args))
self.modified = False
def load_file(self, filename, associate_filename=True):
infile = open(filename, 'r')
flights = []
for line in infile:
if line:
flights.append(flight.from_line(line[:-1],
context=self.context()))
# Don't add until all flight creations are successful, so
# error handling will work properly
for new_flight in flights:
self.add(new_flight)
infile.close()
if associate_filename:
self.filename = filename
def num_flights(self, first=None, before=None, after=None):
# TODO: make more efficient
return len(self.get_range(first, after))
def get_range(self, index=None, first=None, before=None, after=None):
# TODO: make WAY more efficient
result = None
if first is None:
result = self.flights[:]
else:
result = self.flights[-first:]
if after is not None:
result = [f for f in result if f.arr_time >= after]
if before is not None:
result = [f for f in result if f.dept_time <= before]
return result
def get(self, index):
return self.flights[-(index + 1)]
def remove(self, index):
del self.flights[-(index + 1)]
self.modified = True
def add(self, entry):
bisect.insort(self.flights, entry)
entry.add_listener(self)
self.modified = True
def context(self):
if self.flights:
return self.get(0).arr_time
else:
return None
def update(self, _entry):
self.flights.sort()
self.modified = True
def save(self, filename=None):
if filename is None:
filename = self.filename
outfile = open(filename, 'w')
for f in self.flights:
outfile.write(str(f) + '\n')
outfile.close()
self.filename = filename
self.modified = False