-
Notifications
You must be signed in to change notification settings - Fork 0
/
AlgorithmV2_1.py
executable file
·355 lines (308 loc) · 11.7 KB
/
AlgorithmV2_1.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# -*- coding: utf-8 -*-
import re
def autoMatchCourses(prepData, SameTeacherDict):
SameTeacherSect = getSameTeacherSections(prepData, SameTeacherDict)
sectList = getSectList(prepData) # ['CAS CH 131,LEC' ...]
prepData = cleanSameTime(sectList, prepData) # renew prepData
sectList = getSectList(prepData) # renew sectList
scheduleLayers = getScheduleLayers(sectList, prepData)
numSect = len(sectList)
allPlans = getPlans(scheduleLayers, numSect, sectList)
allPlans = filterPlans(allPlans, SameTeacherSect)
print(len(allPlans))
return allPlans
# resulted structure is different from AlgorithmV2
def getSameTeacherSections(prepData, SameTeacherDict):
def getTeachers(sectDict):
teachers = []
for type, sections in sectDict.items():
for section in sections:
if (not section[2] in teachers and section[2] != "Staff"):
teachers.append(section[2])
return teachers
SameTeacherSect = {}
for course, types in SameTeacherDict.items():
if (types[0] != ''):
SameTeacherSect[course] = {}
teachers = getTeachers(prepData[course])
for teacher in teachers:
SameTeacherSect[course][teacher] = {}
for type in types:
if (type in list(prepData[course].keys())):
SameTeacherSect[course][teacher][type] = []
for section in prepData[course][type]:
if (section[2] == teacher):
sectName = section[0] + "-" + \
section[len(
section)-1] + "," + section[3] # this must be the same as section names in scheduleLayers
SameTeacherSect[course][teacher][type].append(
sectName)
return SameTeacherSect
def getSectOfLayer(layer):
sections = {}
for c in range(1-1, len(layer[0])):
for r in range(1-1, len(layer)):
for i in layer[r][c]:
if (any(i)):
if (i in sections):
sections[i].append([r, c])
else:
sections[i] = [[r, c]]
return sections
def getRemoveList(layers, times):
removeList = []
for sectName, layer in layers.items():
for time in times:
if (any(layer[time[0]][time[1]])):
for sect in layer[time[0]][time[1]]:
if ((sect in removeList) == False):
removeList.append(sect)
return removeList
def removeSections(layers, removeList):
newLayers = layers.copy()
for sectName, layer in layers.items():
for c in range(1-1, len(layer[0])):
for r in range(1-1, len(layer)):
removeItems = []
for i in layer[r][c]:
if (i in removeList):
# layer[r][c].remove(i)
removeItems.append(i)
for i in removeItems:
newLayers[sectName][r][c].remove(i)
return newLayers
def removeEmptyLayers(layers):
# see https://stackoverflow.com/questions/1593564/python-how-to-check-if-a-nested-list-is-essentially-empty
def isListEmpty(inList):
if isinstance(inList, list): # Is a list
return all(map(isListEmpty, inList))
return False # Not a list
emptyLayers = []
for sectName, layer in layers.items():
if (isListEmpty(layer)):
emptyLayers.append(sectName)
for emptyLayer in emptyLayers:
layers.pop(emptyLayer)
return layers.copy()
def checkFullDictionary(dict1):
result = True
for key, value in dict1.items():
if (value == None):
result = False
return result
def copyLayers(layers):
newlayers = {}
for key, layer in layers.items():
newlayers[key] = []
i = 0
for rowList in layer:
newlayers[key].append([])
for colList in rowList:
newlayers[key][i].append(colList.copy())
i += 1
return newlayers
def getPlans(scheduleLayers, numSect, sectList):
allPlans = []
onePlan = dict.fromkeys(sectList)
depth = numSect
alist = [0] * numSect
numPlanDone = [0]
planLimit = -1
# see https://stackoverflow.com/questions/4138851/recursive-looping-function-in-python
def recursion(layers, depth):
if (len(layers) <= 0 or depth <= 0):
return
topKey = list(layers.keys())[0]
availableSect = getSectOfLayer(layers[topKey])
layers.pop(topKey)
for section, times in availableSect.items():
if (planLimit != -1 and planLimit == len(allPlans)):
return
removeList = getRemoveList(layers, times)
newlayers = removeSections(copyLayers(layers), removeList)
length = len(layers)
newlayers = removeEmptyLayers(newlayers)
if (len(newlayers) != length): #change layers to newlayers for some reason
continue
onePlan[section.split('-')[1]] = section
if (checkFullDictionary(onePlan) and depth == 1):
allPlans.append(onePlan.copy())
numPlanDone[0] += 1
alist[depth - 1] += 1
print("\r", end="")
print(alist, end="")
print(" %d Zip Plans Done" % (numPlanDone[0]), end="")
recursion(copyLayers(newlayers), depth-1)
recursion(copyLayers(scheduleLayers), depth)
print("")
return allPlans
def cleanSameTime(sectList, prepData):
for sectName in sectList:
course = sectName.split(",")[0]
type = sectName.split(",")[1]
sections = prepData[course][type]
sections_new = []
repeatSect = []
for i in range(0, len(sections)):
aSect = sections[i]
if ((aSect[0] in repeatSect) or (aSect[5]) == "ARR 0: am"):
continue
else:
for j in range(i+1, len(sections)):
bSect = sections[j]
if (aSect[5] == bSect[5]):
repeatSect.append(bSect[0])
aSect[0] = aSect[0] + "/" + bSect[0]
sections_new.append(aSect)
prepData[course][type] = sections_new
return prepData
def getSectList(prepData):
sectList = []
countSect = {}
for course in prepData:
for type in prepData[course]:
sectName = course + "," + type
countSect[sectName] = len(prepData[course][type])
countSect = dict(sorted(countSect.items(), key=lambda item: item[1]))
for sectName in countSect:
sectList.append(sectName)
return sectList
def getScheduleLayers(sectList, prepData):
scheduleLayers = {}
for sectName in sectList:
course = sectName.split(",")[0]
type = sectName.split(",")[1]
sections = prepData[course][type]
oneSchedule = getOneSchedule(sections, newSchedule())
scheduleLayers[sectName] = oneSchedule
return scheduleLayers
def newSchedule(): # indexChange
timeRange = 24*12
weekRange = 7
schedule = []
# oneWeek = ["Time", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
hours = 0
minutes = 0
for i in range(0, timeRange + 1):
schedule.append([])
for j in range(0, weekRange + 1):
schedule[i].append([])
return schedule
def getOneSchedule(sections, sch):
def findIndex(day, hours, minutes): # indexChange
if(day == "M"):
col = 1-1
elif(day == "T"):
col = 2-1
elif(day == "W"):
col = 3-1
elif(day == "R"):
col = 4-1
elif(day == "F"):
col = 5-1
# elif(day == "Sa"):
# col = 6
# elif(day == "Su"):
# col = 7
row = int(1-1 + (12*hours) + (minutes/5))
return [row, col]
def timeConvertion(time):
timeDict = {"hours": 0, "minutes": 0}
hrMin = time[0].split(":")
AmPm = time[1]
if((AmPm == "pm") & (int(hrMin[0]) < 12)):
timeDict["hours"] = int(hrMin[0]) + 12
else:
timeDict["hours"] = int(hrMin[0])
timeDict["minutes"] = int(hrMin[1])
return timeDict
for section in sections:
# Creat display title
ID = section[0]
code = section[len(section) - 1]
type = section[3]
title = ID + "-" + code + "," + type
# Extract time information
timeRawData = section[5].split(",")
timeNewData = []
for oneRawtime in timeRawData:
days = re.findall(r'[A-Z]', oneRawtime)
time = re.findall(
r'([0-9]?[0-9]:[0-9][0-9]) ([a-z]{2})', oneRawtime)
if(len(time) < 2):
return False
start = timeConvertion(time[0])
end = timeConvertion(time[1])
onetime = [days, start, end]
timeNewData.append(onetime)
# Put section in schedule
for oneNewtime in timeNewData:
startHr = oneNewtime[1]["hours"]
startMin = oneNewtime[1]["minutes"]
endHr = oneNewtime[2]["hours"]
endMin = oneNewtime[2]["minutes"]
for day in oneNewtime[0]:
[srow, scol] = findIndex(day, startHr, startMin)
[erow, ecol] = findIndex(day, endHr, endMin)
for i in range(srow, erow+1):
sch[i][ecol].append(title)
return sch
def filterPlans(allPlans, SameTeacherSect):
def hasSameTeacher(newOnePlan, SameTeacherSect):
for course, teacherDict in SameTeacherSect.items():
for teacher, typeDict in teacherDict.items():
shouldBe = len(typeDict)
willBe = 0
for type, sections in typeDict.items():
key = course + "," + type
if (newOnePlan[key] in sections):
willBe += 1
if (shouldBe == willBe):
break
elif (teacher == list(teacherDict.keys())[len(teacherDict) - 1]):
return False
else:
continue
return True
newAllPlans = []
totalNum = len(allPlans)
currentNum = 0
numOfPlansDone = 0
for plan in allPlans:
currentNum += 1
keyList = list(plan.keys())
tempOnePlan = {}
partLen = []
currInd = []
for keys, values in plan.items():
num = 0
if ("/" in values):
tempOnePlan[keys] = []
for id in values.split("-")[0].split("/"):
tempOnePlan[keys].append(id + "-" + values.split("-")[1])
num += 1
else:
tempOnePlan[keys] = [values]
num += 1
partLen.append(num - 1)
currInd.append(0)
currInd[0] -= 1
while(currInd != partLen):
# increment currInd 任意进制进位器*
currInd[0] += 1
for i in range(len(currInd)):
if(currInd[i] > partLen[i]):
currInd[i] = 0
if((i+1) < len(currInd)):
currInd[i+1] += 1
newOnePlan = dict.fromkeys(keyList)
for key in tempOnePlan:
i = keyList.index(key)
newOnePlan[key] = tempOnePlan[key][currInd[i]]
if (hasSameTeacher(newOnePlan, SameTeacherSect)):
numOfPlansDone += 1
newAllPlans.append(newOnePlan)
print("\r%d / %d : %d Unzip Plans Done" %
(currentNum, totalNum, numOfPlansDone), end="")
print("")
return newAllPlans