当前位置: 首页>>代码示例>>Python>>正文


Python Stack.push方法代码示例

本文整理汇总了Python中stack.Stack.push方法的典型用法代码示例。如果您正苦于以下问题:Python Stack.push方法的具体用法?Python Stack.push怎么用?Python Stack.push使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在stack.Stack的用法示例。


在下文中一共展示了Stack.push方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import push [as 别名]
class QueueBaller:
  def __init__(self):
    self.reversed_stack = Stack()
    self.ordered_stack = Stack()

  def __move_from(self, from_stack, to_stack):
      pop_item = from_stack.pop()
      while (pop_item):
        to_stack.push(pop_item)
        if from_stack.is_empty():
          pop_item = False
        else:
          pop_item = from_stack.pop()

  def enqueue(self, item):
    self.reversed_stack.push(item)

  def dequeue(self):
    if self.ordered_stack.is_empty():
      self.__move_from(self.reversed_stack, self.ordered_stack)
      return self.ordered_stack.pop()
    else:
      return self.ordered_stack.pop()

  def peek(self):
    # I suppose we could check ordered_stack, but what if it's empty? do we run the move operation just for peek?
    print(self.reversed_stack.peek())
    print(self.ordered_stack.peek())
    #return self.stack_one.peek()

  def is_empty(self):
    return self.reversed_stack.is_empty() and self.ordered_stack.is_empty()
开发者ID:UnicodeSnowman,项目名称:programming-practice,代码行数:34,代码来源:main.py

示例2: test_peek

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import push [as 别名]
def test_peek():
	s = Stack()
	assert_equals(s.peek(), None)
	s.push(1)
	assert_equals(s.peek(), 1)
	assert_equals(s.count(), 1)
	assert_equals(s.pop(), 1)
开发者ID:suspectpart,项目名称:algorithms,代码行数:9,代码来源:test_stack.py

示例3: infixToPostfix

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import push [as 别名]
def infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.is_empty()) and \
                    (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.is_empty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)
开发者ID:devNaresh,项目名称:DS-Algo,代码行数:32,代码来源:infixToPostfix.py

示例4: dec_converter

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import push [as 别名]
def dec_converter(decNumber, base):
    answer_stack = Stack()

    if base == 16:
        hexa = 'ABCDEF'
        while decNumber >= 1:
            if decNumber % base == 0:
                answer_stack.push(0)
            else:
                remainder = decNumber % base
                if remainder >= 10:
                    answer_stack.push(hexa[remainder - 10])
                else:
                    answer_stack.push(remainder)

            decNumber //= base
    else:
        while decNumber >= 1:
            if decNumber % base == 0:
                answer_stack.push(0)
            else:
                answer_stack.push(decNumber % base)

            decNumber //= base

    answer = ""
    while not answer_stack.isEmpty():
        answer += str(answer_stack.pop())

    return answer
开发者ID:Jiq102938,项目名称:PJC-CS,代码行数:32,代码来源:dec_converter.py

示例5: infix_to_postfix

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import push [as 别名]
def infix_to_postfix(infix_string):
    infix_list = infix_string.split()
    s = Stack()
    output = []
    p = {'(':0, ')':0, '+':1, '-':1, '*':2, '/':2, '^':3}
        
    for e in infix_list:
        if e in 'ABCDEFGHIJKLMNOPQRST' or e in '0123456789':
            output.append(e)
        elif e == '(':
            s.push(e)
        elif e == ')':
            while not s.peek() == '(':
                output.append(s.pop())
            s.pop()
        else:
            if not s.is_empty() and p[e] <= p[s.peek()]:                
                    output.append(s.pop())
            s.push(e)
    
    while not s.is_empty():
        output.append(s.pop())
        
    return " ".join(output)
        
    return result 
开发者ID:southwestjiaotongunivercity,项目名称:Problem-Solving-with-Algorithms-and-DataStructures,代码行数:28,代码来源:3.4.9_infix_to_postfix.py

示例6: test_stack

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import push [as 别名]
    def test_stack(self):
        stack = Stack()
        self.assertEqual(stack.size, 0)

        stack.push(4)
        self.assertEqual(stack.peek(), 4)

        stack.push(36)
        self.assertEqual(stack.peek(), 36)

        stack.push(3)
        self.assertEqual(stack.peek(), 3)

        stack.push(2)
        self.assertEqual(stack.peek(), 2)

        stack.push(1)
        self.assertEqual(stack.peek(), 1)

        self.assertEqual(stack.size, 5)

        self.assertEqual(stack.pop(), 1)
        self.assertEqual(stack.peek(), 2)
        self.assertEqual(stack.pop(), 2)
        self.assertEqual(stack.peek(), 3)
        self.assertEqual(stack.pop(), 3)
        self.assertEqual(stack.peek(), 36)
        self.assertEqual(stack.pop(), 36)
        self.assertEqual(stack.peek(), 4)
        self.assertEqual(stack.pop(), 4)

        self.assertEqual(stack.size, 0)
开发者ID:derekargueta,项目名称:Data-Structures,代码行数:34,代码来源:tests.py

示例7: evaluate_postfix

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import push [as 别名]
def evaluate_postfix(expression, values):
    # create a stack
    stack = Stack()
    # scan expression from left to right
    # for each token
    for token in expression:
        # case 1: operator
        # evalute top 2 things on stack and push result        
        if token in "+-*/":
            operand1 = stack.pop()
            operand2 = stack.pop()
            if token == "+":
                stack.push(operand1 + operand2)
            elif token == "-":
                stack.push(operand2 - operand1)
            elif token == "*":
                stack.push(operand1 * operand2)
            elif token == "/":
                stack.push(operand2 / operand1)            
        
        # case 2: operand
        # add value of operand to the stack        
        else:
            # look up the value of the token and put that on the stack
            stack.push(values[token])
            
    # return result (only thing left on the stack)
    return stack.pop()
开发者ID:swuiojkl,项目名称:CMPUT175,代码行数:30,代码来源:post_eval.py

示例8: evaluate

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import push [as 别名]
def evaluate(pexpr):

    list_post = pexpr.split(" ")
    stack_post = Stack()
    result = 0

    for item in list_post:

        if item.lower() in operands:
            stack_post.push(int(item))

        elif item in list(prec.keys()):
            operand2 = stack_post.pop()
            operand1 = stack_post.pop()

            ## print(operand1, operand2, item)

            result = perform_operation(operand1, operand2, item)

            ## print(result)

            stack_post.push(result)

        else:
            raise RuntimeError("Invalid Expression")

        ## print("pass")

    return stack_post.pop()
开发者ID:kaustubhkurve,项目名称:learn-python,代码行数:31,代码来源:post_eval.py

示例9: evaluate_paranthesis

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import push [as 别名]
def evaluate_paranthesis(expression):
    """
    Evaluate the paranthesis in a given expression.
    
    Arguements:
        expression: a string which only contains paranthesis.
    Returns:
        Boolean: True if balanced, else False.
    Raises:
        None
    """
    stack = Stack()
    expression = expression.replace(" ", "")
    for i in expression:
        if i == "(":
            stack.push(i)
        elif i == ")":
            try:
                stack.pop()
            except IndexError:
                return False
        else:
            return "Invalid symbol!"
    if stack.isEmpty():
        return True
    else:
        return False
开发者ID:jayachandp,项目名称:ds-in-python,代码行数:29,代码来源:paranthesis.py

示例10: buscaAmplitude

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import push [as 别名]
	def buscaAmplitude(self,origin,destination):
		position = origin
		checked = []
		stack = Stack()

		if (position == destination):
			return True
		checked.append(position)
		stack.push(position)

		while(not queue.isEmpty()):
			position = stack.pop()
			if (position == destination):
				return True
			checked.append(position)

			neighbors = self.neighbors(position)
			while(len(neighbors) != 0):
				position = neighbors.pop(0)

				try:
					i = checked.index(position)
				except ValueError:
					i = -1

				if (i == -1):
					if (position == destination):
						return True
					checked.append(position)
					stack.push(position)

		return False
开发者ID:marlonsd,项目名称:EDII-Graph,代码行数:34,代码来源:graph_.py

示例11: is_brackets_blanced

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import push [as 别名]
def is_brackets_blanced(brackets):
    """
    Whether the brackets are pairs
    :param brackets: brackets string
    :return: True or False
    """
    blanced = True
    index = 0
    s = Stack()
    b_left = ['(', '[', '{']
    mapping_num_dict = {'(': 1,
                        ')': 1,
                        '[': 2,
                        ']': 2,
                        '{': 3,
                        '}': 3
                        }
    while index < len(brackets) and blanced:
        if brackets[index] in b_left:
            s.push(brackets[index])
        else:
            if s.isEmpty():
                blanced = False
            else:
                if mapping_num_dict[s.peek()] == mapping_num_dict[brackets[index]]:
                    s.pop()
                else:
                    blanced = False
        index += 1

    return blanced and s.isEmpty()
开发者ID:AlertBear,项目名称:Dstruter,代码行数:33,代码来源:example.py

示例12: TestStack

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import push [as 别名]
class TestStack(unittest.TestCase):

    def setUp(self):
        self.s=Stack()

    def test_afterCreationStackIsEmpty(self):
        self.assertTrue(self.s.is_empty())
        
    def test_afterOnePush_stackIsNotEmpty(self):
        self.s.push(1)
        self.assertFalse(self.s.is_empty())
        
    def test_afterOnePushAndOnePop_stackIsEmpty(self):
        self.s.push(1)
        element = self.s.pop()
        self.assertTrue(self.s.is_empty())
        
    def test_pushedElementsArePoppedInReverseOrder(self):
        self.s.push(1)
        self.s.push(2)
        self.s.push(3)
        self.assertEquals(3, self.s.pop())
        self.assertEquals(2, self.s.pop())
        self.assertEquals(1, self.s.pop())
        
    def test_popWhenEmptyShouldRaiseException(self):
        self.assertRaises(StackEmptyError, self.s.pop)
        
    def test_peekReturnsTopElementWithoutPopping(self):
        self.s.push(0xAA)
        self.assertEquals(0xAA, self.s.peek())
        self.assertEquals(0xAA, self.s.peek())
        
    def test_peekWhenEmptyShouldRaiseException(self):
        self.assertRaises(StackEmptyError, self.s.peek)
开发者ID:doughgle,项目名称:kata_Stack,代码行数:37,代码来源:stack_test.py

示例13: infixToPostfix

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import push [as 别名]
def infixToPostfix(text):
    S = Stack()
    answer = []
    operands = "qwertyuiopasdfghjklzxcvbnm".upper()
    operators = "/*+-"
    precedence = {"+": 0, "-": 0, "*": 1, "/": 1}
    for i in text:
        print(i)
        if i in operands:
            answer.append(i)
        elif i == "(":
            S.push(i)
        elif i == ")":
            while S.peek() != "(":
                answer.append(S.pop())
            S.pop()
        elif i in operators:
            if not S.isEmpty() and S.peek() != "(":
                if precedence[i] < precedence[S.peek()]:
                    answer.append(S.pop())
            S.push(i)

        print(S.list)
        print(answer)
        print("")

    while not S.isEmpty():
        answer.append(S.pop())
    return "".join(answer)
开发者ID:prijindal,项目名称:Interactivepython-Solutions,代码行数:31,代码来源:infixToPostfix.py

示例14: Queueky

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import push [as 别名]
class Queueky():
    def __init__(self):
        self.__s = Stack()

    def enqueue(self, elem):
         self.__s.push(elem)

    def dequeue(self):
        temp = Stack()
        cache = Stack()
        while self.__s.count() > 1:
            temp.push(self.__s.pop())
        while temp.count() > 0:
            cache.push(temp.pop())
        result = self.__s.pop()
        self.__s = cache    
        return result

    def is_empty(self):
        return self.__s.is_empty()

    def top(self):
        return self.__s.top()

    def count(self):
        return self.__s.count()
开发者ID:manafay,项目名称:pythonGO,代码行数:28,代码来源:queueky.py

示例15: StackWithMin

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import push [as 别名]
class StackWithMin(object):
    def __init__(self, top = None):
        self.top = top 

        #store the min values
        self._min = Stack(top) 

    def min(self):
        retval = self._min.peek()
        if retval is None:
            retval = sys.maxsize
        return retval



    def push(self,data):
        new_node = Node(data, self.top)
        self.top = new_node

        if data <= self.min(): 
            self._min.push(data)


    def pop(self):
        if self.top:
            retval = Node(self.top.data)
            self.top = self.top.next

            if retval.data == self.min():
                self._min.pop()
            return retval

    def peek(self):
        if self.top:
            return self.top.data
开发者ID:j1z0,项目名称:cracking_the_code_interview_v5_python,代码行数:37,代码来源:3.2_min_stack.py


注:本文中的stack.Stack.push方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。