-
Notifications
You must be signed in to change notification settings - Fork 0
/
hw7.py
262 lines (217 loc) · 7.15 KB
/
hw7.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# CS 350: Homework 6
# Due: Week of 5/23
# Name: Jacob Bentley
################################################################
# Problem 1
#
# We're going to take the job scheduling problem from class,
# but this time, I want to make sure every job is scheduled.
#
# If I have a set of n jobs where each job is represented
# by a tuple (s,f), give a greedy algorithm to schedule the
# jobs on the fewest number of processors total.
#
# Running Time: O(n*log(n))
################################################################
def schedule(jobs):
"""
>>> schedule([(5,40), (30,35), (6,20), (19, 31), (23, 29), (28, 32)])
[[(6, 20), (23, 29), (30, 35)], [(19, 31)], [(28, 32)], [(5, 40)]]
"""
# List of sublists: each sublist has jobs for a single processor.
sched = []
# Sort jobs in ascending order by finishing time.
jobs.sort(key=lambda x: x[1])
# Collect jobs with compatible start/finish times into sublists.
while jobs:
sched = jobsToProcessor(jobs, sched)
return sched
# Given list of jobs and an existing schedule (list of sublists),
# put compatible jobs into sublist for single processor, add that
# sublist to the overall schedule and return it.
# Note that jobs must be sorted according to finish time.
#
def jobsToProcessor(jobs, sched):
# Add job with earliest finish time to schedule for this processor.
thisProc = [jobs.pop(0)]
for job in jobs:
# Start time is after finish time of last job scheduled.
if job[0] > thisProc[-1][1]:
thisProc.append(job)
jobs.remove(job)
sched.append(thisProc)
return sched
################################################################
# Problem 2
#
# Given a list of strings (strings), find a short string
# (bigstring) such that for every s in string, s is a substring of
# bigstring.
#
# Use the approximation algorithm we gave in class.
#
# Running Time:
################################################################
# Approximation algorithm:
# Look at all the strings and find which two overlap the most.
# Combine those two strings.
# Add that superstring to the set of strings.
# Repeat until there's only one string.
def superstring(strings):
"""
>>> superstring(["CADBC", "CDAABD", "BCDA", "DDCA", "ADBCADC"])
'BCDAABDDCADBCADC'
"""
if len(strings) == 1:
return strings[0]
# `maxOne` and `maxTwo` have most overlap out of `strings`.
maxOne = maxTwo = ""
# Index 0: starting index of overlap for `maxOne`.
# Index 1: starting index of overlap for `maxTwo`.
# Index 2: number of overlapping characters.
maxOverlap = (0, 0, 0)
for string in strings:
for other in strings:
if string == other:
continue
overlap = compareStrings(string, other)
if overlap and overlap[2] > maxOverlap[2]:
maxOne, maxTwo = string, other
maxOverlap = overlap
# Remove maxOne and maxTwo from `strings`, then add their combination.
strings = [s for s in strings if s != maxOne and s != maxTwo]
combined = combineStrings(maxOne, maxTwo, maxOverlap)
strings.append(combined)
return superstring(strings)
# Return tuple indicating overlap between front of `a` and rear of `b`,
# between rear of `a` and front of `b`, or None if no overlap exists.
#
def compareStrings(a, b):
"""
>>> compareStrings("ABC", "DEF")
>>> compareStrings("ABC", "DBA")
(0, 2, 1)
>>> compareStrings("ABC", "CBA")
(2, 0, 1)
>>> compareStrings("ABC", "CAB")
(0, 1, 2)
>>> compareStrings("ABC", "BCA")
(1, 0, 2)
>>> compareStrings("ABCD", "EBCF")
>>> compareStrings("ABCDEF", "CDEFGHIJK")
(2, 0, 4)
>>> compareStrings("ABC", "CDEFAB")
(0, 4, 2)
"""
overlapFront = compareFront(a, b)
overlapBack = compareBack(a, b)
return biggestOverlap(overlapFront, overlapBack)
# Return whichever overlap is larger, or None if no overlap exists.
#
def biggestOverlap(front, back):
if not front and not back:
return None
if front and not back:
return front
if back and not front:
return back
if front[2] > back[2]:
return front
return back
# Return tuple indicating overlap of strings `a` and `b`.
# If no overlap exists, return None.
#
def compareFront(a, b):
# Indices for a and b, respectively.
i = 0
j = len(b) - 1
# Scan b from rear for char that matches first char in a.
while j >= 0 and b[j] != a[i]:
j -= 1
# No match found.
if j == -1:
return None
overlap = 0
# Loop and increment as long as chars match.
while j < len(b) and i < len(a) and b[j] == a[i]:
overlap += 1
i += 1
j += 1
# Make sure we're getting overlap at edges, not internally.
if i == len(a) or j == len(b):
i -= overlap
j -= overlap
else:
return None
# Return starting indices of match for both a and b;
# also return number of matching chars.
return (i, j, overlap)
# Use `compareFront()` to get result, then swap values and return.
#
def compareBack(a, b):
# Get overlap in form (b, a, overlap).
overlap = compareFront(b, a)
# Swap starting indices to preserve (a, b, overlap) ordering.
if overlap:
return (overlap[1], overlap[0], overlap[2])
return None
# Given two strings and their overlap tuple, return combined string.
#
def combineStrings(a, b, overlap):
"""
>>> combineStrings("ABC", "DBA", (0, 2, 1))
'DBABC'
>>> combineStrings("ABC", "CBA", (2, 0, 1))
'ABCBA'
>>> combineStrings("ABC", "CAB", (0, 1, 2))
'CABC'
>>> combineStrings("ABC", "BCA", (1, 0, 2))
'ABCA'
>>> combineStrings("ABCDEF", "CDEFGHIJK", (2, 0, 4))
'ABCDEFGHIJK'
>>> combineStrings("ABC", "CDEFAB", (0, 4, 2))
'CDEFABC'
>>> combineStrings("BCDAABD", "DDCADBCADC", (6, 0, 1))
'BCDAABDDCADBCADC'
"""
startA, startB = overlap[0], overlap[1]
# Back of a overlaps with front of b.
if startA > startB:
return a[:startA] + b
# Front of a overlaps with back of b.
if startA < startB:
return b[:startB] + a
# Match at equal indices: return longer string.
if len(a) > len(b):
return a
return b
################################################################
# Problem 3
#
# Find the shortest path from a to b in a weighted graph g that
# is represented by an adjacency matrix.
#
# You can assume all edge weights are positive.
#
# Running time:
################################################################
# def dijkstra(g, a, b):
# """
# >>> g = [ [(1,3), (2,6)], \
# [(0,3), (4,4)], \
# [(0,6), (3,2), (5,7)], \
# [(2,2), (4,4), (8,1)], \
# [(1,4), (3,4), (6,9)], \
# [(2,7), (6,2), (7,8)], \
# [(4,9), (5,2), (9,4)], \
# [(5,8), (8,3)], \
# [(3,1), (7,3), (9,2)], \
# [(6,4), (8,2)] ]
# >>> dijkstra(g,0,9)
# [0, 2, 3, 8, 9]
# """
# pass
# Enable doctesting
if __name__ == "__main__":
import doctest
doctest.testmod()