def bcc(self): self.reset() clock = 0 stack = ListStack() for i in range(self.n): if self.vertices[i].status == 'UNDISCOVERED': self.BCC(i, clock, stack) stack.pop()
def tsort(self): self.reset() stack = ListStack() for i in range(self.n): if self.vertices[i].status == 'UNDISCOVERED': if not self.TSort(i, stack): stack.clear() break return stack
def _processLoop(self, loopType, loopLines, context): """For loopType == "Fields" repeat lines in loopLines for all fields for loopType == "SFields" repeat lines in loopLines for all sfields for loopType == "MFields" repeat lines in loopLines for all mfields """ if loopType == "Fields" or loopType == "SFields" or loopType == "MFields": fields = self._lookup(loopType, context); else: self.m_log.error("_processLoop: unknown loopType \"%s\"." % loopType); return; localDict = dict([("field", None)]); loopContext = [localDict]; for c in context: loopContext.append(c); for field in fields: localDict["field"] = field; skipStack = ListStack(); skipCurrent = False; for line in loopLines: # handle @@if matchIf = self.m_ifRE.search(line); if matchIf != None: skipStack.push(copy.copy(skipCurrent)); if skipStack.top() == False: if self._lookup(matchIf.group(2), loopContext) == True: skipCurrent = False; else: skipCurrent = True; if matchIf.group(1) == "!": skipCurrent = not skipCurrent; continue; # handle @@else matchElse = self.m_elseRE.search(line); if matchElse != None: if skipStack.top() == False: skipCurrent = not skipCurrent; continue; # handle @@endif matchEndif = self.m_endifRE.search(line); if matchEndif != None: skipCurrent = skipStack.top(); skipStack.pop(); continue; if skipCurrent == True: continue; # a line with regular text - substitute variables and add to output self.m_outLines.append(self._substituteVariables(line, loopContext));
def parenMatch(expr): # symboles de gauche aGauche = "({[" # symboles de droite aDroite = ")}]" # utilise pile S S = ListStack() # pour chaque caractère dans l'expression for c in expr: # si on rencontre un caractère de gauche if c in aGauche: # on l'empile S.push(c) elif c in aDroite: # si on a un symbole de droite if S.is_empty(): # si la pile est vide, pas de match return False if aDroite.index(c) != aGauche.index(S.pop()): # si le symbole à droite ne match pas le symbole à gauche return False # ici, si la pile est vide, l'expression est balancée # sinon il reste un ou des symbole(s) non balancés dans la pile return S.is_empty()
def test_insert(self): rb = RingBuffer(4) rs = RingStack(4) rq = RingQueue(4) ls = ListStack(4) lq = ListQueue(4) for name in TestRingBufferDS.names: rb.insert_keep_old(name) rs.insert(name) rq.insert(name) ls.insert(name) lq.insert(name) print("RingBuffer:", rb) print("RingStack:", rs) print("RingQueue:", rq) print("ListStack:", ls) print("ListQueue:", lq)
def initCounts(self, literalCount): self.totalCount = heapdict.heapdict() self.positiveCount = {} self.countStack = ListStack() totalChanges = {} for literal in literalCount: variable = abs(literal) if variable in totalChanges: totalChanges[variable] += literalCount[literal] else: totalChanges[variable] = literalCount[literal] if literal > 0: self.positiveCount[variable] = literalCount[literal] # - is used to make a max priority queue for variable in totalChanges: self.totalCount[variable] = -totalChanges[variable]
def initCounts(self, literalCount): self.totalCount = {} self.signCount = heapdict.heapdict() self.countStack = ListStack() totalChanges = {} for literal in literalCount: variable = abs(literal) if variable in totalChanges: totalChanges[variable] += literalCount[literal] else: totalChanges[variable] = literalCount[literal] if self.polarity == (literal > 0): # XNOR # - is used to make a max priority queue self.signCount[variable] = -literalCount[literal] for variable in totalChanges: self.totalCount[variable] = totalChanges[variable]
def test_remove(self): rb = RingBuffer(4) rs = RingStack(4) rq = RingQueue(4) ls = ListStack(4) lq = ListQueue(4) for name in TestRingBufferDS.names: rb.insert_keep_old(name) rs.insert(name) rq.insert(name) ls.insert(name) lq.insert(name) print("Before remove: ") print("RingBuffer:", rb) print("RingStack:", rs) print("RingQueue:", rq) print("ListStack:", ls) print("ListQueue:", lq) for i in range(2): rs.remove() rq.remove() ls.remove() lq.remove() print("After remove: ") print("RingBuffer:", rb) print("RingStack:", rs) print("RingQueue:", rq) print("ListStack:", ls) print("ListQueue:", lq)
def evalExp(expr): # on utilise une pile pour les valeurs et une pile pour les opérations valStk = ArrayStack() opStk = ListStack() # tant qu'il y a des jetons en entrée for z in expr: if z.isdigit(): # si chiffre, on l'empile valStk.push(z) if trace: print("chiffre dans la pile", valStk) elif z in "+-*/": # si opération, on voit si on peut l'effectuer if trace: print("opération lue : ", z) repeatOps(z, valStk, opStk) # on empile l'opération opStk.push(z) if trace: print("opération dans la pile", opStk) # on exécute l'opération sur la pile, le cas échéant repeatOps('$', valStk, opStk) # le resultat se trouve sur le top de la pile des valeurs return valStk.top()
def test_init(self): rb = RingBuffer(4) rs = RingStack(4) rq = RingQueue(4) ls = ListStack(4) lq = ListQueue(4) self.assertIsNotNone(rb.head) self.assertEqual(rb.size(), 0) self.assertEqual(rs.top, -1) self.assertEqual(rs.size, 0) self.assertEqual(ls.top, -1) self.assertEqual(ls.size, 0) self.assertEqual(rq.front, -1) self.assertEqual(rq.back, -1) self.assertEqual(rq.size, 0) self.assertEqual(lq.front, -1) self.assertEqual(lq.back, -1) self.assertEqual(lq.size, 0)
def parenMatch(expr): aGauche = "({[" aDroite = ")}]" S = ListStack() for c in expr: if c in aGauche: #si à symbole ouvrant, on empile S.push(c) elif c in aDroite: #si à symbole fermant... if S.is_empty(): #si pile vide pas de match return False if aDroite.index(c) != aGauche.index(S.pop()): #si symbole fermant ne match pas symbole ouvrant return False #match si pile vide, sinon symbole(s) non matché(s) return S.is_empty()
def __init__(self, cnf, numOfVars, plugins, metrics): self.plugins = plugins self.metrics = metrics self.assignmentStack = ListStack() self.externalAssignmentStack = ListStack() self.satisfiedClausesStack = ListStack() self.model = {} self.status = "UNDETERMINED" self.clauses = cnf self.remainingClausesHeap = heapdict.heapdict() self.variableSignedClausesDict = {} for clauseIdx in range(len(self.clauses)): clause = self.clauses[clauseIdx] clauseID = clauseIdx + 1 # Fill heap self.remainingClausesHeap[clauseID] = len(clause) # Fill variable => clauses dictionary for literal in clause: variable = abs(literal) signedClauseID = clauseID if literal > 0 else -clauseID if variable in self.variableSignedClausesDict: self.variableSignedClausesDict[variable].append( signedClauseID) else: self.variableSignedClausesDict[variable] = [signedClauseID] self.remainingVariablesSet = set([]) for clause in cnf: for literal in clause: variable = abs(literal) self.remainingVariablesSet.add(variable) for plugin in self.plugins: plugin.construct(self) # TODO We need to make sure that every variable exists once in each clause # if it exists twice with same polarity reduce one of them # else status = UNSAT !! self.unitPropagation()
def matchBrackets(bracket_array): bracket_stack = ListStack() open_per = ['{', '(', '[', '<'] close_per = ['}', ')', ']', '>'] for i in range(len(bracket_array)): #if the current character is an open bracket add it to the stack if (bracket_array[i] in open_per): bracket_stack.push(bracket_array[i]) continue # if we get past the first character and it's still empty we know it's impossible to have a matching bracket if bracket_stack.isEmpty(): return False top_bracket = bracket_stack.pop() print(top_bracket) bracket_found = False if (top_bracket == open_per[0]) & (bracket_array[i] == close_per[0]): bracket_found == True if not bracket_found: print('Bracket not found') return False # if not bracket_stack.isEmpty(): # return False return True
def fill(self, dictList): """Fill in a template using the contents of the dictionaries in dictList. """ self.m_outLines = []; skipStack = ListStack(); skipCurrent = False; inLoop = False; loopLines = []; # Go through template and find loops, collect their lines in loopLines. # call _processLoop for the loopLines. context = [d for d in dictList]; for lineNum, line in enumerate(self.m_inLines): # handle @@BeginFieldLoop matchBeginFieldLoop = self.m_BeginFieldLoopRE.search(line); if (not skipCurrent) and (matchBeginFieldLoop != None): #self.m_log.debug("fill: line %d -> BeginFieldLoop", lineNum); inLoop = True; continue; # handle @@BeginSFFieldLoop matchBeginSFFieldLoop = self.m_BeginSFFieldLoopRE.search(line); if (not skipCurrent) and (matchBeginSFFieldLoop != None): #self.m_log.debug("fill: line %d -> BeginSFFieldLoop", lineNum); inLoop = True; continue; # handle @@BeginMFFieldLoop matchBeginMFFieldLoop = self.m_BeginMFFieldLoopRE.search(line); if (not skipCurrent) and (matchBeginMFFieldLoop != None): #self.m_log.debug("fill: line %d -> BeginMFFieldLoop", lineNum); inLoop = True; continue; # handle @@BeginProducedEventLoop matchBeginProducedEventLoop = self.m_BeginProducedEventLoopRE.search(line); if (not skipCurrent) and (matchBeginProducedEventLoop != None): #self.m_log.debug("fill: line %d -> BeginProducedEventLoop", lineNum); inLoop = True; continue; # handle loops - do not bother with conditionals they are handled in # _processLoop if (not skipCurrent) and (inLoop == True): # handle @@EndFieldLoop matchEndFieldLoop = self.m_EndFieldLoopRE.search(line); if matchEndFieldLoop != None: #self.m_log.debug("fill: line %d -> EndFieldLoop", lineNum); self._processLoop("Fields", loopLines, context); inLoop = False; loopLines = []; continue; # handle @@EndSFFieldLoop matchEndSFFieldLoop = self.m_EndSFFieldLoopRE.search(line); if matchEndSFFieldLoop != None: #self.m_log.debug("fill: line %d -> EndSFFieldLoop", lineNum); self._processLoop("SFields", loopLines, context); inLoop = False; loopLines = []; continue; # handle @@EndMFFieldLoop matchEndMFFieldLoop = self.m_EndMFFieldLoopRE.search(line); if matchEndMFFieldLoop != None: #self.m_log.debug("fill: line %d -> EndMFFieldLoop", lineNum); self._processLoop("MFields", loopLines, context); inLoop = False; loopLines = []; continue; # handle @@EndProducedEventLoop matchEndProducedEventLoop = self.m_EndProducedEventLoopRE.search(line); if matchEndProducedEventLoop != None: #self.m_log.debug("fill: line %d -> EndProducedEventLoop", lineNum); self._processLoop("ProducedEvents", loopLines, context); inLoop = False; loopLines = []; continue; loopLines.append(line); continue; # handle @@AdditionalIncludes matchAdditionalIncludes = self.m_AdditionIncludesRE.search(line); if matchAdditionalIncludes != None: self._processAdditionalIncludes(dictList); continue; # handle @@AdditionalIncludes matchAdditionalPrioIncludes = self.m_AdditionPrioIncludesRE.search(line); if matchAdditionalPrioIncludes != None: self._processAdditionalPrioIncludes(dictList); continue; # conditionals outside of loops must be treated here # handle @@if matchIf = self.m_ifRE.search(line); if matchIf != None: #self.m_log.debug("fill: line %d -> if", lineNum); skipStack.push(copy.copy(skipCurrent)); if skipStack.top() == False: if self._lookup(matchIf.group(2), dictList) == True: skipCurrent = False; else: skipCurrent = True; if matchIf.group(1) == "!": skipCurrent = not skipCurrent; continue; # handle @@else matchElse = self.m_elseRE.search(line); if matchElse != None: #self.m_log.debug("fill: line %d -> else", lineNum); if skipStack.top() == False: skipCurrent = not skipCurrent; continue; # handle @@endif matchEndif = self.m_endifRE.search(line); if matchEndif != None: #self.m_log.debug("fill: line %d -> endif", lineNum); skipCurrent = skipStack.top(); skipStack.pop(); continue; if skipCurrent == True: continue; # a line with regular text - substitute variables and add to output self.m_outLines.append(self._substituteVariables(line, context)); return self.m_outLines;
class DynamicLargestIndividualSum(BranchDecisionHeuristicInterface, VariableCountPlugin): def __init__(self, polarity): self.polarity = polarity def initCounts(self, literalCount): self.totalCount = {} self.signCount = heapdict.heapdict() self.countStack = ListStack() totalChanges = {} for literal in literalCount: variable = abs(literal) if variable in totalChanges: totalChanges[variable] += literalCount[literal] else: totalChanges[variable] = literalCount[literal] if self.polarity == (literal > 0): # XNOR # - is used to make a max priority queue self.signCount[variable] = -literalCount[literal] for variable in totalChanges: self.totalCount[variable] = totalChanges[variable] def pushCurrentCountsAndDecrease(self, assignedVariable, literalCount): if assignedVariable in literalCount or -assignedVariable in literalCount: print("assignedVariable Exists") previousTotalCount = 0 previousSignCount = 0 if assignedVariable in self.totalCount: previousTotalCount = self.totalCount[assignedVariable] self.totalCount.pop(assignedVariable, None) if assignedVariable in self.signCount: previousSignCount = self.signCount[assignedVariable] self.signCount.pop(assignedVariable, None) totalChanges = {} positiveChanges = {} for literal in literalCount: variable = abs(literal) if variable in totalChanges: totalChanges[variable] += literalCount[literal] else: totalChanges[variable] = literalCount[literal] if self.polarity == (literal > 0): # XNOR positiveChanges[variable] = literalCount[literal] changedVariables = {} for variable in totalChanges: tc = 0 sc = 0 if variable in self.totalCount: tc = self.totalCount[variable] if variable in self.signCount: sc = self.signCount[variable] if sc > 0: raise "sc can't be positive" if tc < 0: raise "sc can't be negative" changedVariables[variable] = (tc, sc) # Apply changes # - is used to decrease the count newValue = self.totalCount[variable] - totalChanges[variable] if newValue < 0: raise "newValue can't be negative" if newValue == 0: self.totalCount.pop(variable, None) else: self.totalCount[variable] = newValue # Apply changes for variable in positiveChanges: # + is used to make a max priority queue newValue = self.signCount[variable] + positiveChanges[variable] if newValue > 0: raise "newValue can't be positive" if newValue == 0: self.signCount.pop(variable, None) else: self.signCount[variable] = newValue self.countStack.push((assignedVariable, previousTotalCount, previousSignCount, changedVariables)) return def popCurrentCounts(self): assignedVariable, previousTotalCount, previousSignCount, changedVariables = self.countStack.pop( ) if previousTotalCount != 0: self.totalCount[assignedVariable] = previousTotalCount if previousSignCount != 0: self.signCount[assignedVariable] = previousSignCount for variable in changedVariables: tc, sc = changedVariables[variable] if tc != 0: self.totalCount[variable] = tc if sc != 0: self.signCount[variable] = sc return def chooseVariableAndValue(self, cnfState): variable, signCount = self.signCount.peekitem() signCount = -signCount tc = self.totalCount[variable] otherSignCount = tc - signCount if tc <= 0 or signCount < 0 or otherSignCount < 0: raise "this can't be true" value = self.polarity if signCount > otherSignCount else not self.polarity return variable, value
def fill(self, dictList): """Fill in a template using the contents of the dictionaries in dictList. """ self.m_outLines = [] skipStack = ListStack() skipCurrent = False inLoop = False loopLines = [] # Go through template and find loops, collect their lines in loopLines. # call _processLoop for the loopLines. context = [d for d in dictList] for lineNum, line in enumerate(self.m_inLines): # handle @@BeginFieldLoop matchBeginFieldLoop = self.m_BeginFieldLoopRE.search(line) if (not skipCurrent) and (matchBeginFieldLoop != None): #self.m_log.debug("fill: line %d -> BeginFieldLoop", lineNum); inLoop = True continue # handle @@BeginSFFieldLoop matchBeginSFFieldLoop = self.m_BeginSFFieldLoopRE.search(line) if (not skipCurrent) and (matchBeginSFFieldLoop != None): #self.m_log.debug("fill: line %d -> BeginSFFieldLoop", lineNum); inLoop = True continue # handle @@BeginMFFieldLoop matchBeginMFFieldLoop = self.m_BeginMFFieldLoopRE.search(line) if (not skipCurrent) and (matchBeginMFFieldLoop != None): #self.m_log.debug("fill: line %d -> BeginMFFieldLoop", lineNum); inLoop = True continue # handle loops - do not bother with conditionals they are handled in # _processLoop if (not skipCurrent) and (inLoop == True): # handle @@EndFieldLoop matchEndFieldLoop = self.m_EndFieldLoopRE.search(line) if matchEndFieldLoop != None: #self.m_log.debug("fill: line %d -> EndFieldLoop", lineNum); self._processLoop("Fields", loopLines, context) inLoop = False loopLines = [] continue # handle @@EndSFFieldLoop matchEndSFFieldLoop = self.m_EndSFFieldLoopRE.search(line) if matchEndSFFieldLoop != None: #self.m_log.debug("fill: line %d -> EndSFFieldLoop", lineNum); self._processLoop("SFields", loopLines, context) inLoop = False loopLines = [] continue # handle @@EndMFFieldLoop matchEndMFFieldLoop = self.m_EndMFFieldLoopRE.search(line) if matchEndMFFieldLoop != None: #self.m_log.debug("fill: line %d -> EndMFFieldLoop", lineNum); self._processLoop("MFields", loopLines, context) inLoop = False loopLines = [] continue loopLines.append(line) continue # handle @@AdditionalIncludes matchAdditionalIncludes = self.m_AdditionIncludesRE.search(line) if matchAdditionalIncludes != None: self._processAdditionalIncludes(dictList) continue # handle @@AdditionalIncludes matchAdditionalPrioIncludes = self.m_AdditionPrioIncludesRE.search( line) if matchAdditionalPrioIncludes != None: self._processAdditionalPrioIncludes(dictList) continue # conditionals outside of loops must be treated here # handle @@if matchIf = self.m_ifRE.search(line) if matchIf != None: #self.m_log.debug("fill: line %d -> if", lineNum); skipStack.push(copy.copy(skipCurrent)) if skipStack.top() == False: if self._lookup(matchIf.group(2), dictList) == True: skipCurrent = False else: skipCurrent = True if matchIf.group(1) == "!": skipCurrent = not skipCurrent continue # handle @@else matchElse = self.m_elseRE.search(line) if matchElse != None: #self.m_log.debug("fill: line %d -> else", lineNum); if skipStack.top() == False: skipCurrent = not skipCurrent continue # handle @@endif matchEndif = self.m_endifRE.search(line) if matchEndif != None: #self.m_log.debug("fill: line %d -> endif", lineNum); skipCurrent = skipStack.top() skipStack.pop() continue if skipCurrent == True: continue # a line with regular text - substitute variables and add to output self.m_outLines.append(self._substituteVariables(line, context)) return self.m_outLines
class DynamicLargestCombinedSum(BranchDecisionHeuristicInterface, VariableCountPlugin): def initCounts(self, literalCount): self.totalCount = heapdict.heapdict() self.positiveCount = {} self.countStack = ListStack() totalChanges = {} for literal in literalCount: variable = abs(literal) if variable in totalChanges: totalChanges[variable] += literalCount[literal] else: totalChanges[variable] = literalCount[literal] if literal > 0: self.positiveCount[variable] = literalCount[literal] # - is used to make a max priority queue for variable in totalChanges: self.totalCount[variable] = -totalChanges[variable] def pushCurrentCountsAndDecrease(self, assignedVariable, literalCount): if assignedVariable in literalCount or -assignedVariable in literalCount: print("assignedVariable Exists") previousTotalCount = 0 previousPositiveCount = 0 if assignedVariable in self.totalCount: previousTotalCount = self.totalCount[assignedVariable] self.totalCount.pop(assignedVariable, None) if assignedVariable in self.positiveCount: previousPositiveCount = self.positiveCount[assignedVariable] self.positiveCount.pop(assignedVariable, None) totalChanges = {} positiveChanges = {} for literal in literalCount: variable = abs(literal) if variable in totalChanges: totalChanges[variable] += literalCount[literal] else: totalChanges[variable] = literalCount[literal] if literal > 0: positiveChanges[variable] = literalCount[literal] changedVariables = {} for variable in totalChanges: tc = 0 pc = 0 if variable in self.totalCount: tc = self.totalCount[variable] if variable in self.positiveCount: pc = self.positiveCount[variable] if pc < 0: raise "pc can't be negative" changedVariables[variable] = (tc, pc) # Apply changes # + is used to make a max priority queue newValue = self.totalCount[variable] + totalChanges[variable] if newValue > 0: raise "tc can't be positive" if newValue == 0: self.totalCount.pop(variable, None) else: self.totalCount[variable] = newValue # Apply changes for variable in positiveChanges: # - is used to decrease the count newValue = self.positiveCount[variable] - positiveChanges[variable] if newValue < 0: raise "pc can't be negative" if newValue == 0: self.positiveCount.pop(variable, None) else: self.positiveCount[variable] = newValue self.countStack.push((assignedVariable, previousTotalCount, previousPositiveCount, changedVariables)) return def popCurrentCounts(self): assignedVariable, previousTotalCount, previousPositiveCount, changedVariables = self.countStack.pop( ) if previousTotalCount != 0: self.totalCount[assignedVariable] = previousTotalCount if previousPositiveCount != 0: self.positiveCount[assignedVariable] = previousPositiveCount for variable in changedVariables: tc, pc = changedVariables[variable] if tc != 0: self.totalCount[variable] = tc if pc != 0: self.positiveCount[variable] = pc return def chooseVariableAndValue(self, cnfState): variable, tc = self.totalCount.peekitem() tc = -tc pc = self.positiveCount[variable] nc = tc - pc if tc <= 0 or pc < 0 or nc < 0: raise "this can't be true" value = pc > nc return variable, value
class CNFState(): # - self.remainingClauses: an array of clauses has unassigned variables # - self.satisfiedClausesStack: a stack of satisfied clauses at each step # - self.assignmentStack: a running stack of variable assignment def __init__(self, cnf, numOfVars, plugins, metrics): self.plugins = plugins self.metrics = metrics self.assignmentStack = ListStack() self.externalAssignmentStack = ListStack() self.satisfiedClausesStack = ListStack() self.model = {} self.status = "UNDETERMINED" self.clauses = cnf self.remainingClausesHeap = heapdict.heapdict() self.variableSignedClausesDict = {} for clauseIdx in range(len(self.clauses)): clause = self.clauses[clauseIdx] clauseID = clauseIdx + 1 # Fill heap self.remainingClausesHeap[clauseID] = len(clause) # Fill variable => clauses dictionary for literal in clause: variable = abs(literal) signedClauseID = clauseID if literal > 0 else -clauseID if variable in self.variableSignedClausesDict: self.variableSignedClausesDict[variable].append( signedClauseID) else: self.variableSignedClausesDict[variable] = [signedClauseID] self.remainingVariablesSet = set([]) for clause in cnf: for literal in clause: variable = abs(literal) self.remainingVariablesSet.add(variable) for plugin in self.plugins: plugin.construct(self) # TODO We need to make sure that every variable exists once in each clause # if it exists twice with same polarity reduce one of them # else status = UNSAT !! self.unitPropagation() def getRemainingVariablesSet(self): return self.remainingVariablesSet def assignmentLength(self): return len(self.externalAssignmentStack) def getModel(self): return self.model def getStatus(self): return self.status def lastAssignment(self): variable, value, state = self.externalAssignmentStack.top() return variable, value, state def pushAssignment(self, variable, value): self.externalAssignmentStack.push((variable, value, "BRANCH")) self.pushAssignmentInternal(variable, value, "BRANCH") self.unitPropagation() return self.status, variable, value def pushAssignmentInternal(self, variable, value, state): self.assignmentStack.push((variable, value, state)) self.model[variable] = value if variable in self.remainingVariablesSet: self.remainingVariablesSet.remove(variable) else: print("Not in set") for plugin in self.plugins: plugin.assignmentPushed(self, variable, value) # we need to deduce self.deduceNewVariable(variable, value) return self.status, variable, value def flipLastAssignment(self): self.metrics.incrementCounter("flip") variable, value = self.popLastAssignment() value = not value self.externalAssignmentStack.push((variable, value, "FLIPPED")) self.pushAssignmentInternal(variable, value, "FLIPPED") self.unitPropagation() return self.status, variable, value def backtrackUntilUnflipped(self): self.metrics.incrementCounter("backtrack") while len(self.externalAssignmentStack) > 0: _, _ = self.popLastAssignment() if len(self.externalAssignmentStack) == 0: break _, _, state = self.externalAssignmentStack.top() if state == "BRANCH": # unflipped break if len(self.externalAssignmentStack) == 0: self.status = "UNSAT" return self.status # The new variable is already added def deduceNewVariable(self, variable, value): # Deduction Step # /Find/ remaining clauses which contain currentVariable # (preferably from the least to the highest in terms of unsatisfied literals) # do either: # - if literal value is True => /Remove/ that clause from remaining clauses # - if literal value is False => /Reduce/ the number of unsatisfied literals # Removed clausess are put in satisfiedClausesStack variableSignedClauseIDs = self.variableSignedClausesDict[variable] satisfiedClauseIDs = [] newPriorities = {} for signedClauseID in variableSignedClauseIDs: clauseID = abs(signedClauseID) if clauseID in self.remainingClausesHeap: if (value == True and signedClauseID > 0) or (value == False and signedClauseID < 0): satisfiedClauseIDs.append(clauseID) else: newPriorities[ clauseID] = self.remainingClausesHeap[clauseID] - 1 if newPriorities[clauseID] == 0: self.status = "CONFLICT" return satisfiedClausesPriorities = {} for clauseID in satisfiedClauseIDs: satisfiedClausesPriorities[clauseID] = self.remainingClausesHeap[ clauseID] self.remainingClausesHeap.pop(clauseID) self.satisfiedClausesStack.push(satisfiedClausesPriorities) for plugin in self.plugins: plugin.satisfiedClausesPushed(self, variable, satisfiedClausesPriorities) for clauseID in newPriorities: self.remainingClausesHeap[clauseID] = newPriorities[clauseID] if len(self.remainingClausesHeap) == 0: self.status = "SAT" return self.status = "UNDETERMINED" def popLastAssignment(self): while len(self.assignmentStack) > 0: variable, value, state = self.assignmentStack.pop() self.model.pop(variable, None) self.remainingVariablesSet.add(variable) for plugin in self.plugins: plugin.assignmentPoped(self, variable, value) if self.status != "CONFLICT": variableSignedClauseIDs = self.variableSignedClausesDict[ variable] # For clauses inside remainingClausesHeap, their priority need to be increased for signedClauseID in variableSignedClauseIDs: clauseID = abs(signedClauseID) if clauseID in self.remainingClausesHeap: self.remainingClausesHeap[ clauseID] = self.remainingClausesHeap[clauseID] + 1 # Then add previously satisfied clauses from satisfiedClausesStack # which will come with the correct previous priority satisfiedClausesPriorities = self.satisfiedClausesStack.pop() for clauseID in satisfiedClausesPriorities: self.remainingClausesHeap[ clauseID] = satisfiedClausesPriorities[clauseID] for plugin in self.plugins: plugin.satisfiedClausesPoped(self, variable, satisfiedClausesPriorities) self.status = "UNDETERMINED" if state != "UNIT": self.externalAssignmentStack.pop() break self.status = "UNDETERMINED" return variable, value def unitPropagation(self): # Unit Propagation # /Find clause with the least number/ of unsatisfied literals # if the number of unsatisfied literal is 1 # /Remove/ this clause, assign a proper value to the varialbe, # Then go back to Deduce step if self.status == "CONFLICT": return while len(self.remainingClausesHeap) > 0 and self.status != "CONFLICT": clauseID, priority = self.remainingClausesHeap.peekitem() if priority > 1: break self.metrics.incrementCounter("unit") clauseIdx = clauseID - 1 # Which variable is unassigned? for literal in self.clauses[clauseIdx]: variable = abs(literal) if variable in self.model: pass else: # unassigned variable # choose a value for it to satisfy the clause value = True if literal > 0 else False self.pushAssignmentInternal(variable, value, "UNIT") break return
def benchMarkTest(): """ BenchMark IntStack vs Python deque. """ n = 10000000 intStack = IntStack(n) # Implemenation using IntStack module (5.046 sec) start = time.process_time() for i in range(0, n): intStack.push(i) for i in range(0, n): intStack.pop() end = time.process_time() print("IntStack Time: ", (end - start)) # Implemenation using ListStack module (29.609375 sec) listStack = ListStack() start = time.process_time() for i in range(0, n): listStack.push(i) for i in range(0, n): listStack.pop() end = time.process_time() print("ListStack Time: ", (end - start)) # Implemenation using ArrayStack module (7.09375 sec) arrayStack = ArrayStack(0) start = time.process_time() for i in range(0, n): arrayStack.push(i) for i in range(0, n): arrayStack.pop() end = time.process_time() print("ArrayStack Time: ", (end - start)) # Implementation using collections.deque (1.28125 sec) # Python stack can be implemented using deque class from collections module. # Deque is preferred over list in the cases where we need quicker append and # pop operations from both the ends of the container, as deque provides an O(1) # time complexity for append and pop operations as compared to list which # provides O(n) time complexity. # Same methods on deque as seen in list are used, append() and pop(). stackDeque = deque() # deque is slower when you give it an initial capacity. start = time.process_time() for i in range(0, n): stackDeque.append(i) for i in range(0, n): stackDeque.pop() end = time.process_time() print("DequeStack Time: ", (end - start)) # Implemenation using queue module (33.765625 sec) # Queue module also has a LIFO Queue, which is basically a Stack. Data is # inserted into Queue using put() function and get() takes data out from the Queue. lifoStack = LifoQueue(maxsize=n) start = time.process_time() for i in range(0, n): lifoStack.put(i) for i in range(0, n): lifoStack.get() end = time.process_time() print("LIFOStack Time: ", (end - start))
def __init__(self, reader): self.m_log = logging.getLogger("FCDContentHandler"); self.m_reader = reader; self.m_container = None; self.m_elemStack = ListStack();
def setUp(self): self.stacks = [] self.stacks.append(ListStack()) self.stacks.append(ArrayStack(0)) self.stacks.append(IntStack(2))
def main(): print('\n\nCreating empty ListStack named "a" of size 4') a = ListStack(4) print('Creating empty ListQueue named "b" of size 4') b = ListQueue(4) print('Creating empty Stack named "c" of size 4') c = Stack(4) print('Creating empty Queue named "d" of size 4') d = Queue(4) print("") print("PEEKING ON AN (a)LISTSTACK, (b)QUEUESTACK, (c)STACK, (d)QUEUE") print('peek on a', a.peek(), 'currently contains', a.__str__()) print('peek on b', b.peek(), 'currently contains', b.__str__()) print('peek on c', c.peek(), 'currently contains', c.__str__()) print('peek on d', d.peek(), 'currently contains', d.__str__()) print("") print( " ----------- INSERTING VALUES ON (a)LISTSTACK, (b)QUEUESTACK, (c)STACK, (d)QUEUE ---------------" ) for val in range(6): print('inserting', val, 'into both a(ListStack), b(ListQueue), c(Stack), d(Queue)\n') print("") a.insert(val) b.insert(val) c.push(val) d.enqueue(val) print('peek on a', a.peek(), 'currently contains', a.__str__()) print('peek on b', b.peek(), 'currently contains', b.__str__()) print('peek on c', c.peek(), 'currently contains', c.__str__()) print('peek on d', d.peek(), 'currently contains', d.__str__()) print("") print( " ----------- REMOVING VALUES ON (a)LISTSTACK, (b)QUEUESTACK, (c)STACK, (d)QUEUE ---------------" ) for i in range(4): print('Removing', i, 'into both a(ListStack), b(ListQueue), c(Stack), d(Queue)') print('Before removing', a.peek(), 'from a', a.__str__()) a.remove() print('peek on a', a.peek(), 'after removing', a.__str__()) print("") print('Before removing', b.peek(), 'from b', b.__str__()) b.remove() print('peek on a', a.peek(), 'after removing', b.__str__()) print("") print('Before removing', c.peek(), 'from c', c.__str__()) c.pop() print('peek on c', c.peek(), 'after removing', c.__str__()) print("") print('Before removing', c.peek(), 'from d', d.__str__()) d.dequeue() print('peek on d', c.peek(), 'after removing', d.__str__()) print("") l = [10, 2, 23, 35, 76] print( " ----------- INSERTING USER DEFINED VALUES ON (a)LISTSTACK, (b)QUEUESTACK, (c)STACK, (d)QUEUE ---------------" ) for val in l: print('inserting', val, 'into both a and b and c which is user defined') a.insert(val) b.insert(val) c.push(val) d.enqueue(val) print('peek on a', a.peek(), 'currently contains', a.__str__()) print('peek on b', a.peek(), 'currently contains', b.__str__()) print('peek on b', c.peek(), 'currently contains', c.__str__()) print('peek on d', d.peek(), 'currently contains', d.__str__()) print("") print("") print( " ----------- REMOVING USER DEFINED VALUES ON (a)LISTSTACK, (b)QUEUESTACK, (c)STACK, (d)QUEUE ---------------" ) for i in l: print('Removing', i, 'into both a(ListStack), b(ListQueue), c(Stack), d(Queue)') print('Before removing', a.peek(), 'from a', a.__str__()) a.remove() print('peek on a', a.peek(), 'after removing', a.__str__()) print("") print('Before removing', b.peek(), 'from b', b.__str__()) b.remove() print('peek on a', a.peek(), 'after removing', b.__str__()) print("") print('Before removing', c.peek(), 'from c', c.__str__()) c.pop() print('peek on c', c.peek(), 'after removing', c.__str__()) print("") print('Before removing', c.peek(), 'from d', d.__str__()) d.dequeue() print('peek on d', c.peek(), 'after removing', d.__str__()) print("")
def __init__(self, reader): self.m_log = logging.getLogger("FCDContentHandler") self.m_reader = reader self.m_container = None self.m_elemStack = ListStack() self.m_parseField = False
class FCDContentHandler(xml.sax.handler.ContentHandler): """A SAX-parser content handler class for .fcd files """ def __init__(self, reader): self.m_log = logging.getLogger("FCDContentHandler"); self.m_reader = reader; self.m_container = None; self.m_elemStack = ListStack(); def startDocument(self): self.m_log.debug("startDocument"); self.m_elemStack.clear(); def endDocument(self): self.m_log.debug("endDocument"); self.m_container.finalize(); self.m_reader.setFieldContainer(self.m_container); def startElement(self, name, attr): self.m_log.debug("startElement: %s", name); if name == "FieldContainer": container = FieldContainer(); self.m_container = container; self.m_elemStack.push(container); elif name == "Field": field = Field(); self.m_elemStack.top().addField(field); self.m_elemStack.push(field); elif name == "ProducedEvent": producedEvent = ProducedEvent(); self.m_elemStack.top().addProducedEvent(producedEvent); self.m_elemStack.push(producedEvent); else: self.m_log.error("startElement: unknown element: %s", name); return; for i, attrName in enumerate(attr.getNames()): self.m_log.debug("%s attr: %d - %s - %s", name, i, attrName, attr[attrName]); self.m_elemStack.top().setFCD(attrName, attr[attrName]); def endElement(self, name): self.m_log.debug("endElement: %s", name); self.m_elemStack.pop(); def characters(self, content): self.m_log.debug("characters: |%s|", content); currDesc = self.m_elemStack.top().getFCD("description"); if currDesc == None: self.m_elemStack.top().setFCD("description", content.lstrip(" \t")); else: currDesc += content.lstrip(" \t"); self.m_elemStack.top().setFCD("description", currDesc);
class FCDContentHandler(xml.sax.handler.ContentHandler): """A SAX-parser content handler class for .fcd files """ def __init__(self, reader): self.m_log = logging.getLogger("FCDContentHandler") self.m_reader = reader self.m_container = None self.m_elemStack = ListStack() self.m_parseField = False def startDocument(self): self.m_log.debug("startDocument") self.m_elemStack.clear() def endDocument(self): self.m_log.debug("endDocument") self.m_container.finalize() self.m_reader.setFieldContainer(self.m_container) def startElement(self, name, attr): self.m_log.debug("startElement: %s", name) if name == "FieldContainer": container = FieldContainer() self.m_container = container self.m_elemStack.push(container) elif name == "Field": field = Field() self.m_elemStack.top().addField(field) self.m_elemStack.push(field) self.m_parseField = True else: self.m_log.error("startElement: unknown element: %s", name) return for i, attrName in enumerate(attr.getNames()): self.m_log.debug("%s attr: %d - %s - %s", name, i, attrName, attr[attrName]) self.m_elemStack.top().setFCD(attrName, attr[attrName]) def endElement(self, name): self.m_log.debug("endElement: %s", name) if (self.m_parseField == True): if (self.m_elemStack.top().getFCD("osg2Ignore") == "true"): field = self.m_elemStack.top() self.m_elemStack.pop() self.m_elemStack.top().subField(field) else: self.m_elemStack.pop() self.m_parseField = False else: self.m_elemStack.pop() def characters(self, content): self.m_log.debug("characters: |%s|", content) currDesc = self.m_elemStack.top().getFCD("description") if currDesc == None: self.m_elemStack.top().setFCD("description", content.lstrip(" \t")) else: currDesc += content.lstrip(" \t") self.m_elemStack.top().setFCD("description", currDesc)
print("Peek on Queue returns") print(list1.peek()) print("Reseting the Queue with size 0") list1 = Queue(0) print("Now trying to add 1") list1.enqueue(1) print("Now trying to print Queue") list1.__str__() print("Now trying to dequeqe") list1.dequeue() print("-------------------") print("Test case of ListStack") sizeOfLS = int(input("Enter size of ListStack")) a = ListStack(sizeOfLS) print("Adding 1") a.insert(1) print('peek ', a.peek(), 'currently contains', a) print("Adding 2") a.insert(2) print("Adding 3") a.insert(3) print("ListStack as of now ", a) print("Adding 4.") a.insert(4) print("ListStack as of now ", a) print("capacity of ListStack is", a.capacity()) print("Removing ", a.peek()) a.remove() print(a)
def test(): """ :return: """ print('\n\n\nCreating empty Stack named "a" of size 3') a = Stack(4) for val in range(7): print('Inserting ', val, 'into a') a.push(val) print(" " + a.__str__()) print("--------------------") for i in range(2): print('Removing from a') a.pop() print(" " + a.__str__()) print('\n\n\n+++++++++++++++++++++++++++++++++') print('+++++++++++++++++++++++++++++++++') print('+++++++++++++++++++++++++++++++++') print('\n\n\nCreating empty ListStack named "a" of size 3') a = ListStack(4) for val in range(7): print('Inserting ', val, ' into a') a.insert(val) print(" " + a.__str__()) print("--------------------") for i in range(2): print('Removing from a') a.remove() print(" " + a.__str__()) print('\n\n\n+++++++++++++++++++++++++++++++++') print('+++++++++++++++++++++++++++++++++') print('+++++++++++++++++++++++++++++++++') print('\n\n\nCreating empty ListQueue named "a" of size 3') a = ListQueue(4) for val in range(7): print('Inserting ', val, ' into a') a.insert(val) print(" " + a.__str__()) print("--------------------") for i in range(2): print('Removing from a') a.remove() print(" " + a.__str__()) print('\n\n\n+++++++++++++++++++++++++++++++++') print('+++++++++++++++++++++++++++++++++') print('+++++++++++++++++++++++++++++++++') print('\n\n\nCreating empty Ring Buffer Queue named "a" of size 3') a = Queue(4) for val in range(7): print('inserting', val, 'into a') a.enqueue(val) print(" " + a.__str__()) print("--------------------") for i in range(2): print('removing from a') a.dequeue() print(" " + a.__str__())
class JeroslowWangOneSided(BranchDecisionHeuristicInterface, JeroslowWangPlugin): def initCounts(self, literalScore): self.literalScore = heapdict.heapdict() self.countStack = ListStack() for literal in literalScore: # - is used to make a max priority queue self.literalScore[literal] = -literalScore[literal] return def pushCurrentCountsAndDecrease(self, assignedVariable, literalScore): if assignedVariable in literalScore or -assignedVariable in literalScore: raise "assignedVariable Exists" positiveScore = 0 if assignedVariable in self.literalScore: positiveScore = self.literalScore[assignedVariable] self.literalScore.pop(assignedVariable, None) negativeScore = 0 if -assignedVariable in self.literalScore: negativeScore = self.literalScore[-assignedVariable] self.literalScore.pop(-assignedVariable, None) changedLiterals = {} for literal in literalScore: score = self.literalScore[literal] changedLiterals[literal] = score # + is used to decrease the count newValue = self.literalScore[literal] + literalScore[literal] if newValue > 0: raise "newValue can't be positive" if abs(newValue) < 0.000001 and newValue != 0: raise "very small" if newValue == 0: self.literalScore.pop(literal, None) else: self.literalScore[literal] = newValue self.countStack.push( (assignedVariable, positiveScore, negativeScore, changedLiterals)) return def popCurrentCounts(self): assignedVariable, positiveScore, negativeScore, changedLiterals = self.countStack.pop( ) if positiveScore != 0: self.literalScore[assignedVariable] = positiveScore if negativeScore != 0: self.literalScore[-assignedVariable] = negativeScore for literal in changedLiterals: score = changedLiterals[literal] if score != 0: self.literalScore[literal] = score return def chooseVariableAndValue(self, cnfState): literal, score = self.literalScore.peekitem() score = -score if score <= 0: raise "this can't be true" variable = abs(literal) value = literal > 0 return variable, value
def test_ListStack(): s = ListStack() print(s.empty()) s.top() s.pop() s.push(1) s.push(2) s.push(3) print(s.top()) s.pop() print(s.top())