Example #1
0
def evaluate(s):
    op = stack.stack()
    num = stack.stack()
    for i in s:
        if i.isdigit():
            num.push(int(i))
        elif i == "*":
            op.push(i)
        elif i == "+":
            op.push(i)
        elif i == "-":
            op.push(i)
        elif i == ")":
            num1 = num.pop()
            num2 = num.pop()
            operator = op.pop()
            if operator == "+":
                num.push(num1 + num2)
            elif operator == "*":
                num.push(num1 * num2)
            else:
                num.push(num1 - num2)
        print "OP", op.data
        print "NUM", num.data
    print "OP", op.data
    print "NUM", num.data
    return num.pop()
Example #2
0
def parse_expression(expr):
    start_index_operand = 0
    operand_stack = stack()
    operator_stack = stack()
    result = 0
    for i in range(0, len(expr)):
        if (expr[i] == '+' or expr[i] == '-' or expr[i] == '*'
                or expr[i] == '/' or expr[i] == '='):
            operand = expr[start_index_operand:i]
            operator = expr[i]
            start_index_operand = i + 1
            if (operator_stack.is_empty() == True):
                operand_stack.push(operand)
                operator_stack.push(operator)
            else:
                previous_operator = operator_stack.pop()
                if (previous_operator == '/' or previous_operator == '*'):
                    result = calculate(operand_stack.pop(), operand,
                                       previous_operator)
                    operand_stack.push(result)
                    operator_stack.push(operator)
                if (previous_operator == '+'):
                    operator_stack.push(previous_operator)
                    operator_stack.push(operator)
                    operand_stack.push(operand)
                if (previous_operator == '-'):
                    operator_stack.push('+')
                    operator_stack.push(operator)
                    operand = '-' + operand
                    operand_stack.push(operand)
    return reduce(operand_stack, operator_stack)
Example #3
0
 def __init__ (self, capacity):
     self.__capacity = capacity;
     self.s = stack();
     self.currSt = s;
     # creeat stack to hold prev and next stack reference
     self.sstack = stack();  # top value holds node cotaing prev and next of curr stack
     node = Node();
     sstack.push(node);
Example #4
0
def generateTree(policy):
    stringStack = stack()
    nodeStack = stack()
    i = 0
    while i < len(policy):
        word = ''
        if policy[i] == '(':
            word = '('
            stringStack.push(word)
            i += 1
        elif policy[i] == ')':
            word = ')'
            r = node()
            if stringStack.top() == 'not':
                r = None
            else:
                r = nodeStack.top()
                nodeStack.pop()
            l = nodeStack.top()
            nodeStack.pop()
            
            n = node(stringStack.top(), l, r)
            nodeStack.push(n)
            stringStack.pop()
            stringStack.pop()
            
            i += 1
        elif policy[i] == ' ':
            i += 1
        else:
            i, word = nextAttribute(policy, i)
            if word == 'and' or word == 'or' or word == 'not':
                stringStack.push(word)
            else:
                n = node(word)
                nodeStack.push(n)

    r = None
    if stringStack.top() != 'not':
        r = nodeStack.top()
        nodeStack.pop()
    
    l = nodeStack.top()
    nodeStack.pop()
    
    root = node(stringStack.top(), l, r)
    stringStack.pop()
    
    return root
Example #5
0
def generateTree(policy):
    stringStack = stack()
    nodeStack = stack()
    i = 0
    while i < len(policy):
        word = ''
        if policy[i] == '(':
            word = '('
            stringStack.push(word)
            i += 1
        elif policy[i] == ')':
            word = ')'
            r = node()
            if stringStack.top() == 'not':
                r = None
            else:
                r = nodeStack.top()
                nodeStack.pop()
            l = nodeStack.top()
            nodeStack.pop()

            n = node(stringStack.top(), l, r)
            nodeStack.push(n)
            stringStack.pop()
            stringStack.pop()

            i += 1
        elif policy[i] == ' ':
            i += 1
        else:
            i, word = nextAttribute(policy, i)
            if word == 'and' or word == 'or' or word == 'not':
                stringStack.push(word)
            else:
                n = node(word)
                nodeStack.push(n)

    r = None
    if stringStack.top() != 'not':
        r = nodeStack.top()
        nodeStack.pop()

    l = nodeStack.top()
    nodeStack.pop()

    root = node(stringStack.top(), l, r)
    stringStack.pop()

    return root
def buildParseTree(fpexp):
    fplist = fpexp.split()
    print(fplist)
    pStack = stack()
    eTree = binaryTree('')
    pStack.push(eTree)
    currentTree = eTree
    for i in fplist:
        print(i)
        if i == '(':
            currentTree.insertLeft('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()
        elif i not in ['+', '-', '*', '/', ')']:
            # jika i adalah operand
            currentTree.setRootVal(int(i))
            parent = pStack.pop()
            currentTree = parent
        elif i in ['+', '-', '*', '/', ')']:
            # jika i adalah operator
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif i == ')':
            currentTree = pStack.pop()
        else:
            raise ValueError
    return eTree
Example #7
0
    def test_push(self):
        s = stack()

        s.push(1)
        expected = 1
        size = s.size()
        msg = f'After push(1) stack size should be {expected}, got {size}'
        self.assertEqual(size, expected, msg)

        s.push(2)
        expected = 2
        size = s.size()
        msg = f'After push(2) stack size should be {expected}, got {size}'
        self.assertEqual(size, expected, msg)

        got = s.pop()
        expected = 2
        msg = f'Got {got} from stack, expected {expected}'
        self.assertEqual(got, expected, msg)

        got = s.pop()
        expected = 1
        msg = f'Got {got} from stack, expected {expected}'
        self.assertEqual(got, expected, msg)

        got = s.isEmpty()
        expected = True
        msg = f"Got '{got}' from stack, expected '{expected}'"
        self.assertEqual(got, expected, msg)
Example #8
0
    def test_push(self):
        s = stack()

        s.push(1)
        expected = 1
        size = s.size()
        msg = f'After push(1) stack size should be {expected}, got {size}'
        self.assertEqual(size, expected, msg)

        s.push(2)
        expected = 2
        size = s.size()
        msg = f'After push(2) stack size should be {expected}, got {size}'
        self.assertEqual(size, expected, msg)

        got = s.pop()
        expected = 2
        msg = f'Got {got} from stack, expected {expected}'
        self.assertEqual(got, expected, msg)

        got = s.pop()
        expected = 1
        msg = f'Got {got} from stack, expected {expected}'
        self.assertEqual(got, expected, msg)

        got = s.isEmpty()
        expected = True
        msg = f"Got '{got}' from stack, expected '{expected}'"
        self.assertEqual(got, expected, msg)
Example #9
0
def toInfix(s):
    a=ahihi.stack()
    i=0
    while (i<len(s)):
        if (s[i].isdigit()):
            x=""
            j=i
            while ((j<len(s) and (s[j].isdigit()) or (j<len(s)-1 and s[j]=='.' and s[j+1].isdigit()))):
                x=x+s[j]
                j=j+1
            new_s.append(x)
            i=j-1
        elif (s[i]=='('):
            a.push(s[i])
        elif (s[i]=='+' or s[i]=='-' or s[i]=='*' or s[i]=='/'or s[i]=='^'):
            while (a.size() and not(check(s[i],a.top())) and a.top()!="("):
                new_s.append(a.top())
                a.pop()
            a.push(s[i])
        elif (s[i]==')'):
            while (a.top()=='+' or a.top()=='-' or a.top()=='*' or a.top()=='/' or a.top()=='^'):
                new_s.append(a.top())
                a.pop()
            if (a.top()=='('):
                a.pop()
        i=i+1
    while (a.size()):
        new_s.append(a.top())
        a.pop()
    return new_s
Example #10
0
def check_para(paren_string):
    s = stack()
    is_balanced = True
    index = 0
    if (paren_string == ''):
        is_balanced = False
        return 'Empty'
    else:
        while len(paren_string) > index and is_balanced:
            paren = paren_string[index]
            if paren in "{([ ":
                if s.push(paren):
                    s.push(paren)
                else:
                    is_balanced = False

            else:
                if (s.isEmpty):
                    is_balanced = True
                if not is_match(s.peek(), paren):
                    is_balanced = False
                s.pop()
            index += 1

        if is_balanced and s.isEmpty():
            return "Balanced"
        else:
            return "Not Balanced"
def expression_evaluation(expression):
    expression = expression.split(" ")
    print(expression)
    parent_stack = stack.stack()
    current = binarytree.binarytree()
    for item in expression:
        if item == "(":
            #print("(", item)
            current.insert_left()
            parent_stack.push(current)
            #print("(", parent_stack)
            #print("(", current)
            current = current.get_left_tree()
        elif item in ["+", "-", "*", "/"]:
            #print("+-*/", item)
            current.set_root_val(item)
            current.insert_right()
            parent_stack.push(current)
            #print("+-/*", parent_stack)
            #print("+-/*", current)
            current = current.get_right_tree()
        elif item == ")":
            #print(")", item)
            if not parent_stack.is_empty():
                current = parent_stack.pop()
        else:
            #print("number", item)
            current.set_root_val(item)
            #print("number",current)
            if not parent_stack.is_empty():
                current = parent_stack.pop()
    return current
def balancedparan(e):
    import stack
    a=stack.stack()
    d={'{':'}','[':']','(':')','/*':'*/'}
    for i in e:
        if i in d.keys():
            a.push(i)
        elif i in d.values():
            if a.isempty()==True:
                print("ERROR...Unbalanced...")
                return
            else:
                b=a.pop()
                if d[b]==i:
                    pass
                else:
                    print("Error...Unbalanced.....")
                    return
        else:
            pass

    if a.isempty()==True:
        print("OK.....Balanced...")
    else:
        print("Error.....Unbalanced......")
Example #13
0
    def __init__(self):
        #attributes
        self.A = stack.stack()
        self.B = stack.stack()
        self.C = stack.stack()
        self.stacks = [self.A, self.B, self.C]

        #need to change to 0,1,2
        self.allMoves = ((0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1))
        self.path = []
        self.validMoves = []
        self.lastMove = ()
        self.steps = 0

        #setup stacks
        self.setup()
Example #14
0
def checker(symbolString):
    s = stack()

    balanced = True

    index = 0

    while index < len(symbolString) and balanced:

        symbol = symbolString[index]

        if symbol == "(":
            s.push(symbol)

        else:
            if s.isEmpty():
                balanced = False
            else:
                s.pop()

        index += 1

    if balanced and s.isEmpty():
        return True
    else:
        return False
def postfoxThis(infixEquation = None):
	prec = {}
	prec["*"] = 3
	prec["/"] = 3
	prec["+"] = 2
	prec["-"] = 2
	prec["("] = 1
	opstack = stack.stack()
	output = []
	infixList = infixEquation.split()
	operand = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
	operanum = "0123456789"
	operator = ["*","/","+","-"]
	op = ""
	for i in infixList[0]:
		if i in operand or i in operanum:
			output.append(i)
		elif i == "(":
			opstack.push(i)
		elif i == ")":
			while opstack.peek() != "(":
				op = opstack.pop()
				output.append(op)
			opstack.pop()
		else:
			while (not opstack.isEmpty()) and (prec[opstack.peek()] >= prec[i]):
				output.append(opstack.pop())
			opstack.push(i)
	while not opstack.isEmpty():
		output.append(opstack.pop())
	return " ".join(output)
Example #16
0
def main():
    while 1:
        print('Choose an option:\n')
        print('1. Create Stack')
        print('2. Delete Stack')
        print('3. Push')
        print('4. Pop')
        print('5. Print Stack Data')
        print('6. Top Element')
        print('7. No. of Element')
        choice = int(input('Enter your choice: '))
        if choice == 1:
            stk = stack()
            print('Stack Created...')
        elif choice == 2:
            del stk
            print('Stack Deleted...')
        elif choice == 3:
            element = int(input('Enter the no. to be inserted...'))
            stk.push(element)
        elif choice == 4:
            print('Element Poped=', stk.pop())
        elif choice == 5:
            print(stk)
        elif choice == 6:
            print('Top element:', stk.top())
        elif choice == 7:
            print('Size= ', stk.size())

        proceed = input('Enter y to proceed: ')
        if proceed != 'y':
            break
Example #17
0
def syntaxChecker(string):
    stack_sy = stack.stack()
    # 注意这里的 opens、closes 变量的设置,顺序均为 小括号、中括号、大括号,
    # 定义为顺序一致是为了方便的通过 下标 判断括号是否配对
    opens = "([{"
    closes = ")]}"
    balanced = True
    # 循环遍历字符串
    for i in string:
        # 如果是左括号,直接入栈
        if i in opens:
            stack_sy.push(i)
        # 如果是右括号,进入判断
        elif i in closes:
            # 判断1:栈是否为空,为空则 false
            if stack_sy.is_Empty():
                balanced = False
                break
            # 判断2:栈不为空,则取出栈顶左括号
            else:
                j = stack_sy.pop()
                # 判断3:在初始化变量 opens、closes 中查找左括号和右括号的下标,如果下标不同则说明不匹配
                if opens.find(j) != closes.find(i):
                    balanced = False
                    break
    # 遍历结束,如果栈不为空,说明左侧有多余左括号,false
    if not stack_sy.is_Empty():
        balanced = False
    return balanced
Example #18
0
 def test_push_method(self):
   '''
   make sure the push method works as it should
   '''
   data = 'some bit of artbitrary data'
   new_stack = stack()
   self.assertTrue(new_stack.push(data))
   self.assertEqual(new_stack.head.data, data)
Example #19
0
 def test_push_method(self):
     '''
 make sure the push method works as it should
 '''
     data = 'some bit of artbitrary data'
     new_stack = stack()
     self.assertTrue(new_stack.push(data))
     self.assertEqual(new_stack.head.data, data)
Example #20
0
	def __init__(self):
		#attributes
		self.A = stack.stack()
		self.B = stack.stack()
		self.C = stack.stack()
		self.stacks = [self.A,self.B,self.C]
		
		#need to change to 0,1,2
		self.allMoves = ((0,1) , (0,2) , (1,0) , (1,2) ,
									(2,0) , (2,1))
		self.path = []
		self.validMoves = []
		self.lastMove = ()
		self.steps = 0
									
		#setup stacks				
		self.setup()
Example #21
0
    def test_size(self):
        s = stack()
        s.extend(range(100))  # have not allowed stack(range(100))

        expected = 100
        size = s.size()
        msg = f'Stack size should be {expected}, got {size}'
        self.assertEqual(size, expected, msg)
Example #22
0
    def test_size(self):
        s = stack()
        s.extend(range(100))    # have not allowed stack(range(100))

        expected = 100
        size = s.size()
        msg = f'Stack size should be {expected}, got {size}'
        self.assertEqual(size, expected, msg)
Example #23
0
def test_push():
    test = s.stack()
    test.push(1)
    test.push(2)
    test.push(3)
    assert test.pop() == 3
    assert test.pop() == 2
    assert test.pop() == 1
Example #24
0
def set_class(queue):
    global class_data
    for node in queue:
        if not node.get('name'):
            class_data.append(
                base.Base(trace_id=node['trace_id'], level=node['level']))
        elif node.get('name') == 'db':
            class_data.append(
                db.DB(node['project'], node['service'], node['level'],
                      node['trace_id'], node['parent_id'], node['starttime'],
                      node['time']))
        elif node.get('name') == 'wsgi':
            class_data.append(
                wsgi.WSGI(node['project'], node['service'], node['level'],
                          node['trace_id'], node['parent_id'],
                          node['starttime'], node['time']))
        elif node.get('name') == 'compute_api':
            class_data.append(
                compute.compute(node['project'], node['service'],
                                node['level'], node['trace_id'],
                                node['parent_id'], node['starttime'],
                                node['time']))
        elif node.get('name') == 'rpc':
            class_data.append(
                rpc.RPC(node['project'], node['service'], node['level'],
                        node['trace_id'], node['parent_id'], node['starttime'],
                        node['time']))
        elif node.get('name') == 'driver':
            class_data.append(
                driver.driver(node['project'], node['service'], node['level'],
                              node['trace_id'], node['parent_id'],
                              node['starttime'], node['time']))
        elif node.get('name') == 'vif_driver':
            class_data.append(
                vif_driver.vif(node['project'], node['service'], node['level'],
                               node['trace_id'], node['parent_id'],
                               node['starttime'], node['time']))
        elif node.get('name') == 'neutron_api':
            class_data.append(
                neutron.neutron(node['project'], node['service'],
                                node['level'], node['trace_id'],
                                node['parent_id'], node['starttime'],
                                node['time']))
        elif node.get('name') == 'volume_api':
            class_data.append(
                volume.volume(node['project'], node['service'], node['level'],
                              node['trace_id'], node['parent_id'],
                              node['starttime'], node['time']))
        elif node.get('name') == 'nova_image':
            class_data.append(
                nova.nova(node['project'], node['service'], node['level'],
                          node['trace_id'], node['parent_id'],
                          node['starttime'], node['time']))
        else:
            class_data.append(
                stack.stack(node['project'], node['service'], node['level'],
                            node['trace_id'], node['parent_id'],
                            node['starttime'], node['time']))
Example #25
0
def dfs(maze, start, end, walls):
    """
	This function runs DFS on the maze to find a path from start to end
	"""
    m_stack = stack()  #Inits a stack to store nodes in
    visited = copy.deepcopy(walls)
    prev = copy.deepcopy(
        maze)  #Keeps track of the previous for a particular node
    opened = 0
    m_stack.push(start)  #Put in start into the stack
    prev[start[0]][start[1]] = None

    #Iterate until the stack is empty
    while not m_stack.isEmpty():
        opened += 1
        current = m_stack.pop()  #Remove a node from the stack

        if visited[current[0]][current[1]] == False:
            visited[current[0]][current[1]] = True
            if current[0] == end[0] and current[1] == end[
                    1]:  #If you have reached the end, return
                break
            else:  #This checks all neighbors, top, right, bottom, left, to see if we can move there
                if not (current[0] - 1) < 0 and not visited[current[0] -
                                                            1][current[1]]:
                    prev[current[0] - 1][current[1]] = [
                        current[0], current[1]
                    ]  #Set the previous for the neighbor to be the current node
                    m_stack.push([current[0] - 1,
                                  current[1]])  #Push it onto the stack

                if not (current[1] + 1) >= len(
                        walls[0]) and not visited[current[0]][current[1] + 1]:
                    prev[current[0]][current[1] + 1] = [current[0], current[1]]
                    m_stack.push([current[0], current[1] + 1])

                if not (current[0] + 1) >= len(walls) and not visited[
                        current[0] + 1][current[1]]:
                    prev[current[0] + 1][current[1]] = [current[0], current[1]]
                    m_stack.push([current[0] + 1, current[1]])

                if not (current[1] -
                        1) < 0 and not visited[current[0]][current[1] - 1]:
                    prev[current[0]][current[1] - 1] = [current[0], current[1]]
                    m_stack.push([current[0], current[1] - 1])

    path = copy.deepcopy(maze)
    current = end
    steps = 0
    while maze[current[0]][current[
            1]] != 'P':  #Go to the end point, and build out the solution path back to the start by following the previous values for each node
        current = prev[current[0]][current[1]]
        path[current[0]][current[1]] = '.'
        steps += 1  #Keep track of the number of steps you have taken
    path[start[0]][start[1]] = 'P'

    return path, steps, opened  #Return the path, solution cost, and number of nodes expanded
Example #26
0
def temptest():
    s = stack()
    text = "123455"
    s.push(int(text))
    print(s.size())
    print(s.top())
    print(s.size())
    print(s.pop())
    print(s.size())
Example #27
0
	def __init__(self):	#defining __init__ function
		self.my_stack = stack()	#the stack
		self.Q = []	#list of states
		self.A = []	#list containing input alphabet
		self.Z = []	#list containing stack input alphabet
		self.T = []	#list containing transitions
		self.S = []	#list containing start state
		self.F = []	#list containing final accepting states
		self.current = self.S	#initializing the current state
Example #28
0
 def parse(self, response):
     target = response.url
     
     url = []
     followLink = stack()
     x = []
     #print('fetch')
     #print(response.meta['depth'])
     print('iniciou')
 def __init__(self):
     #table stack
     self.tbmng = table_manager()
     #offset stack
     self.offset = stack()
     self.mcode = []
     self.nextquad = 0
     self.temp = 0
     self.layer = 0
Example #30
0
def main():

    h2o.init()

    # Load some example binary response data
    x, y, train, test, family = prep_data_example()

    # Load stacking utils
    source_stack_utils()
    from stack import make_Z, get_cvpreds, stack, metapredict

    # Cross-validation & training of base models
    # Above we train an abitrary assortment of base models
    models = cvtrain_base_models(x=x, y=y, train=train, family=family)

    # Define a NN-GLM metalearner
    metalearner = H2OGeneralizedLinearEstimator(family='binomial',
                                                non_negative=True)

    # Fit the stacked ensemble / Super Learner
    metafit = stack(models=models,
                    metalearner=metalearner,
                    response_frame=train[y],
                    seed=1,
                    keep_levelone_data=True)

    # Generate ensemble prediction on the test set
    pred, basepred = metapredict(models=models,
                                 metafit=metafit,
                                 test_data=test)

    # TO DO: Add metafit.ensemble_performance()
    # Evaluate ensemble test performance
    preds = pred[2].as_data_frame(True)
    labels = test[y].as_data_frame(True)
    fpr, tpr, thresholds = metrics.roc_curve(labels, preds, pos_label=1)
    auc = metrics.auc(fpr, tpr)
    print str(auc) + "  " + "H2O Ensemble"

    # Evaluate base learner test set performance (for comparison)
    for model in models:
        bperf = model.model_performance(test_data=test)
        print str(bperf.auc()) + "  " + model.model_id

    # 0.792100100148  H2O Ensemble
    # 0.781849246474  GBM_model_python_1471654758738_1
    # 0.782052358716  GBM_model_python_1471654758738_816
    # 0.769195957061  GBM_model_python_1471654758738_1837
    # 0.729095165124  DeepLearning_model_python_1471654758738_3028
    # 0.691393671746  DeepLearning_model_python_1471654758738_3057
    # 0.724608757556  DeepLearning_model_python_1471654758738_3086
    # 0.78333120166  DRF_model_python_1471654758738_3115
    # 0.787051172219  DRF_model_python_1471654758738_3896
    # 0.687091955549  GLM_model_python_1471654758738_4639

    # In this example, ensemble test AUC was 0.792 and the top base learner was 0.783
Example #31
0
def sort(unsorted):
    sortedStack = stack()

    while len(unsorted):
        top = unsorted.pop()
        while len(sortedStack) and sortedStack.peek() < top:
            unsorted.push(sortedStack.pop())
        sortedStack.push(top)

    return sortedStack
def convertToBinary(number = None, binaryRep = None):
	binaryRep = stack.stack()
	while number > 0:
		digit = number % 2
		number = number // 2
		binaryRep.push(digit)
	binaryNumber = ""
	for i in range(binaryRep.size()):
		binaryNumber = binaryNumber + str(binaryRep.pop())
	return str(binaryNumber)
Example #33
0
def dfs_preorder_iterative(root, result):
    todo = stack()
    todo.append(root)
    while len(todo):
        node = todo.pop()
        if node.right:
            todo.append(node.right)
        if node.left:
            todo.append(node.left)
        result.append( node.value )
Example #34
0
 def test_stack_clear_method(self):
     '''
 push a few values to a new stack, then clear it and test that it is clear
 '''
     new_stack = stack()
     new_stack.push('first data')
     new_stack.push('second_data')
     new_stack.push('third_data')
     new_stack.clear()
     self.assertIsNone(new_stack.head)
Example #35
0
 def test_push_then_pop(self):
     '''
 push a value, then pop it. Data in should be correct, and result stack should
 not be poppable
 '''
     new_stack = stack()
     data = 'some bit of arbitrary data'
     new_stack.push(data)
     self.assertEqual(new_stack.pop(), data)
     self.assertFalse(new_stack.pop())
Example #36
0
def preOrder(node):
    stack = stack.stack()
    stack.push(node)
    while not stack.empty():
        top = stack.pop()
        print('{}'.format(top.data))
        if top.right != None:
            stack.push(top.right)
        if top.left != None:
            stack.push(top.left)
Example #37
0
 def test_stack_clear_method(self):
   '''
   push a few values to a new stack, then clear it and test that it is clear
   '''
   new_stack = stack()
   new_stack.push('first data')
   new_stack.push('second_data')
   new_stack.push('third_data')
   new_stack.clear()
   self.assertIsNone(new_stack.head)
Example #38
0
 def test_push_then_pop(self):
   '''
   push a value, then pop it. Data in should be correct, and result stack should
   not be poppable
   '''
   new_stack = stack()
   data = 'some bit of arbitrary data'
   new_stack.push(data)
   self.assertEqual(new_stack.pop(), data)
   self.assertFalse(new_stack.pop())
Example #39
0
def dfs_preorder_iterative(root, result):
    todo = stack()
    todo.append(root)
    while len(todo):
        node = todo.pop()
        if node.right:
            todo.append(node.right)
        if node.left:
            todo.append(node.left)
        result.append(node.value)
Example #40
0
 def __init__(self, co):
     """dict 是保存 局部变量的,不要误认为是 f.local 了
     它在新的 frame 中和 f.global 是相同的.
     不要问我为什么这样处理因为 Python 源码的实现也是这样处理的."""
     self.co_consts = co.consts
     self.co_cellvars = co.cellvars
     self.co_freevars = co.freevars
     self.co_name = co.name
     self.co_names = co.names
     self.co_nlocals = co.nlocals
     self.co_argcount = co.argcount
     self.co_varnames = co.varnames
     self.stack = stack(size=co.stacksize)
     self.global_ = None
     self.local = None
     self.bulitin = None
     self.dict = copy.deepcopy(co.dict)
     self.index = None
     self.co_code = self.code_to_int(co.code)
     self.blocks = stack(size=20)  # python 中块级操作的堆栈.方便运行时堆栈的恢复
Example #41
0
 def test_push_pop_twice(self):
   '''
   push two values then pop the second. The head should be the first value pushed 
   '''
   new_stack = stack()
   data1 = 'first'
   data2 = 'second'
   new_stack.push(data1)
   new_stack.push(data2)
   new_stack.pop()
   self.assertEqual(new_stack.head.data, data1)
Example #42
0
 def test_push_pop_twice(self):
     '''
 push two values then pop the second. The head should be the first value pushed 
 '''
     new_stack = stack()
     data1 = 'first'
     data2 = 'second'
     new_stack.push(data1)
     new_stack.push(data2)
     new_stack.pop()
     self.assertEqual(new_stack.head.data, data1)
def baseConverter(number,base):
	digits = "0123456789ABCDEF"
	otherBase = stack.stack()
	while number > 0:
		digit = number % base
		number = number // base
		otherBase.push(digit)
	
	newString = ''
	for i in range(otherBase.size()):
		newString = newString + str(digits[otherBase.pop()])
	return str(newString)
Example #44
0
def main():
    filenames = ('1.txt', '2.txt', '3.txt', '4.txt', '5.txt', '6.txt', '7.txt',
                 '8.txt', '9.txt', '10.txt')
    lines = []
    words_list = []
    token_list = []
    #idents_dict = {}
    result = (False, 0, 0)

    for index in range(len(filenames)):
        with open('test/5/' + filenames[index], 'r', encoding='utf-8') as fr:

            global file
            file += 1
            global count
            count = 0

            for line in fr:
                lines.append(line.strip().lower())
            lines = [x for x in lines if x != '']
            # print(lines)

            words_list = recog_words(lines)
            # print(words_list)

            for elem in words_list:
                if elem[1] == 'basic' or elem[1] == 'calcu' or elem[
                        1] == 'border':
                    token_list.append((words[elem[1]][elem[0]], elem[0]))
                else:
                    token_list.append((elem[1], elem[0]))
            print(token_list)
            addr = stack(len(token_list))

            result = gramma_analyze(token_list, 0, addr)
            if result[0]:
                print('语法正确,表达式的的位置在' + str(result[2].pop()[1]))
            else:
                print('语法错误,错误出自' + str(result[1]) + '位置.')
            '''
            with open('result/2/'+filenames[index], 'w', encoding='utf-8') as fw:
                for elem in words_list:
                    if elem[1] == 'basic' or elem[1] == 'calcu' or elem[1] == 'border':
                        fw.write(
                            '('+str(words[elem[1]][elem[0]])+','+str(elem[0])+')\n')
                    else:
                        fw.write('('+elem[1]+','+elem[0]+')\n')
            '''

            lines.clear()
            token_list.clear()
            words_list.clear()
            addr.empty()
Example #45
0
    def test_isempty(self):
        s = stack()

        got = s.isEmpty()
        expected = True
        msg = f"Got '{got}' from stack, expected '{expected}'"
        self.assertEqual(got, expected, msg)

        s.push(1)
        got = s.isEmpty()
        expected = False
        msg = f"Got '{got}' from stack, expected '{expected}'"
        self.assertEqual(got, expected, msg)
Example #46
0
    def test_isempty(self):
        s = stack()

        got = s.isEmpty()
        expected = True
        msg = f"Got '{got}' from stack, expected '{expected}'"
        self.assertEqual(got, expected, msg)

        s.push(1)
        got = s.isEmpty()
        expected = False
        msg = f"Got '{got}' from stack, expected '{expected}'"
        self.assertEqual(got, expected, msg)
Example #47
0
    def __init__(self, pts):
        """
            Computes the convex hull of the specified array of points.
            
            pts is a list of elements of class 'Point2D'.

        """
        self.hull = stack()
        self.concave = [] # indices of concave segments (in the original array)

        N = len(pts)
       
        # Populate 'index' field, i.e. tag the points with their (original) index
        points = [Point2D(p.x, p.y, i) for i, p in enumerate(pts)]
        
        # Preprocess so that points[0] has lowest y-coordinate; break ties by x-coordinate
        # points[0] is an extreme point of the convex hull
#        points.sort(key = lambda p: (p.y, p.x)])
#        p0 = points[0]
        # (alternatively, could do easily (and cleanly) in linear time)
        p0 = min(points, key = points[0].yOrder)
               
        points.sort(key = p0.polarOrder)
        
        self.hull.push(p0)    # p[0] is first extreme point

        # find index k1 of first point not equal to points[0]
        k1 = 1
        for k1 in range(1, N):
            if p0 != points[k1]:
                break
        else:
            return  # all points equal
        
        # find index k2 of first point not collinear with points[0] and points[k1]
        k2 = k1 + 1
        for k2 in range(k1 + 1, N):
            if p0.ccw(points[k1], points[k2]) != 0:
                break
        self.hull.push(points[k2-1]) # points[k2-1] is second extreme point

        # Graham scan; note that points[N-1] is extreme point different from points[0]
        for i in range(k2, N):
            top = self.hull.pop()
            while self.hull and self.hull.peek().ccw(top, points[i]) <= 0:
                # top is concave
                self.concave.append(top.index)
                top = self.hull.pop()
            self.hull.push(top)
            self.hull.push(points[i])
Example #48
0
def dfs_inorder_iterative(root, result):
    todo = stack()
    todo.append( root )
    last = None
    while len(todo):
        node = todo.pop()
        if node:
            if not last or (last.left is node or last.right is node):
                todo.append( node )
                todo.append( node.left )
            else:
                result.append( node.value )
                todo.append( node.right )
            last = node 
Example #49
0
def dfs_inorder_iterative_visit2(root, result):
    '''cleaner and more understandable than visit1.'''
    todo = stack()
    todo.append( root )
    while len(todo):
        node = todo.pop()
        if node:
            if not node.visited:
                node.visited = True
                todo.append( node ) # readding the node for second visit
                todo.append( node.left )
            else:
                result.append( node.value )
                todo.append( node.right )
Example #50
0
 def inOrderTraversalIteration(self, root):
     result = list()
     s = stack()
     p = root
     while(p is not None or not s.empty()):
         if p is not None:
             s.push(p)
             p = p.left
         else:
             node = s.top()
             s.pop()
             result.append(node.val)
             p = node.right
     return result
Example #51
0
 def walk(self):
   stk = stack.stack()
   stk.push(self.startDir)
   while not stk.empty():
     directory = stk.top()
     stk.pop()
     files = os.listdir(directory)
     for thisFile in files:
       name = os.path.join(directory, thisFile)
       if os.path.isdir(name):
         stk.push( name )
       else:
         self.files.append( thisFile )
         self.dirs.append( name )
Example #52
0
 def __recognize(self, text, token_stream):
     """Runs the automaton over an input stream of tokens. For use with the
     output of a Scanner instance. The last token MUST be
     ('$', '$', length_of_text)."""
     S = stack(self)
     #toki = iter(token_stream)
     S.shift(None, None, 0)
     S.count_active = 1
     prev_tok = INITIAL_TOKEN
     for cur_tok in token_stream:
         if len(S.active) == 0:
             if not self.error_detected(text, prev_tok,
                                        S.previously_active):
                 break
             else:
                 continue
         prev_tok = cur_tok
         #print "pre reduce", S.active
         # Reduce phase
         for i, node in S.enumerate_active():  # S.active may grow
             state = node.data
             for r, rule in ifilter(lambda x: x[0] == 'R',
                                    self.ACTION[state][cur_tok[0]]):
                 #print "R", i, len(S.active), node
                 S.reduce(node, rule)
             i += 1
         # Check if there are accepting states, and return their outputs
         if cur_tok[0] == '$':
             acc = S.accepts()
             if acc:
                 return acc
             else:
                 self.error_detected(text, cur_tok, S.active)
         #print "pre shift", S.active
         # Shift phase
         S.count_active = len(S.active)
         for node in (S.active[i] for i in xrange(len(S.active))):
             state = node.data
             for r, state in ifilter(lambda x: x[0] == 'S',
                                    self.ACTION[state][cur_tok[0]]):
                 S.shift(node, (cur_tok,), state)
         #print "pre merge", S.active
         # Merge states
         S.merge()
         # A little bit of feedback
         if self.debug:
             print "On token", cur_tok
             S.dump()
     return None
Example #53
0
def dfs(maze, start, end, walls):
	"""
	This function runs DFS on the maze to find a path from start to end
	"""
	m_stack = stack()			#Inits a stack to store nodes in
	visited = copy.deepcopy(walls)
	prev = copy.deepcopy(maze)		#Keeps track of the previous for a particular node
	opened = 0
	m_stack.push(start)				#Put in start into the stack
	prev[start[0]][start[1]] = None			
	
	#Iterate until the stack is empty 
	while not m_stack.isEmpty():
		opened += 1
		current = m_stack.pop()				#Remove a node from the stack

		if visited[current[0]][current[1]] == False:	
			visited[current[0]][current[1]] = True
			if current[0] == end[0] and current[1] == end[1]:	#If you have reached the end, return
				break
			else: #This checks all neighbors, top, right, bottom, left, to see if we can move there
				if not (current[0] - 1) < 0 and not visited[current[0] -1][current[1]]:
					prev[current[0] -1][current[1]] = [current[0], current[1]]				#Set the previous for the neighbor to be the current node
					m_stack.push([current[0] -1 , current[1]])								#Push it onto the stack
	
				if not (current[1] + 1) >= len(walls[0]) and not visited[current[0]][current[1] + 1]:
					prev[current[0]][current[1] + 1] = [current[0], current[1]]
					m_stack.push([current[0], current[1] + 1]) 

				if not (current[0] + 1) >= len(walls) and not visited[current[0] + 1][current[1]]:
					prev[current[0] + 1][current[1]] = [current[0], current[1]]
					m_stack.push([current[0] + 1 , current[1]])
	
				if not (current[1] - 1) < 0 and not visited[current[0]][current[1] - 1]:
					prev[current[0]][current[1] - 1] = [current[0], current[1]]
					m_stack.push([current[0] , current[1] - 1])

	path = copy.deepcopy(maze)
	current = end
	steps = 0
	while maze[current[0]][current[1]] != 'P':				#Go to the end point, and build out the solution path back to the start by following the previous values for each node
		current = prev[current[0]][current[1]]
		path[current[0]][current[1]] = '.'
		steps += 1											#Keep track of the number of steps you have taken
	path[start[0]][start[1]] = 'P'

	return path, steps, opened								#Return the path, solution cost, and number of nodes expanded
Example #54
0
    def balance(self, rule):
        st = stack.stack()
        s1 = ''
        s2 = ''
        for l in rule:
            if l == '[':
                st.push(l)
            elif l == ']':
                t = st.pop()
                if t == 0:
                    s1 = s1 + '['
        t = st.pop()
        while t != 0:
            s2 = s2 + ']'
            t = st.pop()

        return s1 + rule + s2
def modWithTwo(decNum):
    listAngka = stack()
    hasilBagi = decNum
    pembagi = 26
    while hasilBagi > 1:
        # / menghasilkan nilai bulet, bukan koma2
        processNum = hasilBagi
        hasilBagi = hasilBagi/pembagi
        hasilMod = processNum-((hasilBagi)*pembagi)
        listAngka.push(hasilMod)
    listAngka.push(hasilBagi)

    binaryString = ""
    while not listAngka.isEmpty():
        hasil = True
        binaryString = binaryString + str(listAngka.pop())
    return binaryString
 def push(self,e):
     if (currSt.size() == self.capacity):
         newStack = stack();
         # change the next value of old stack node
         oldNode = sstack.pop();
         oldNode.next = newStack;
         sstack.push(oldNode);
         
         # creat new node to hold prev value of new stack, update next when we creat new stack
         newNode = node(currSt);
         
         # update newNode prev pointer to currSt
         
         newNode.prev = currSt;
         sstack.push(newNode);
         
         # update currSt to newStack
         currSt = newStack;
     currSt.push(e);
Example #57
0
    def isSymmetricIteration(self, root):
        s = stack()
        s.push(root.left)
        s.push(root.right)
        while(not s.empty()):
            p = s.top()
            s.pop()
            q = s.top()
            s.pop()

            if p is None and q is None:
                continue
            if p is None or q is None:
                return False
            if p.val != q.val:
                return False
            s.push(p.left)
            s.push(q.right)
            s.push(p.right)
            s.push(q.left)
        return True
Example #58
0
    def test_pop(self):
        s = stack()
        s.extend([1, 2, 3])

        got = s.pop()
        expected = 3
        msg = f'Got {got} from stack, expected {expected}'
        self.assertEqual(got, expected, msg)

        got = s.pop()
        expected = 2
        msg = f'Got {got} from stack, expected {expected}'
        self.assertEqual(got, expected, msg)

        got = s.pop()
        expected = 1
        msg = f'Got {got} from stack, expected {expected}'
        self.assertEqual(got, expected, msg)

        msg = 'Expected IndexError from pop() of empty list'
        with self.assertRaises(IndexError, msg=msg):
            s.pop()