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


Python Stack.peek方法代码示例

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


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

示例1: answer

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import peek [as 别名]
def answer(a): #使用一个栈从两个方向获取数值
    c = Queue()
    
    b = Stack()
    cur = a.element()
    while cur != None:
        b.push(Node(cur.value))
        cur = cur.next
    
    c = Queue()
    a_pre = a.element()
    add_a_pre = False # queue length is odd
    while a.element().value != b.peek().value and \
          a_pre.value != b.peek().value:
        if a_pre.value == b.peek().value:
            add_a_pre = True
        a_pre = a.remove()
        c.add(Node(a_pre.value))
        c.add(Node(b.pop().value))
        
    if add_a_pre: # odd
        c.add(Node(a_pre.value))
    else: # even
        c.add(Node(a.remove().value))
        
    return c
开发者ID:michael-7845,项目名称:python-puzzle,代码行数:28,代码来源:reorder_list.py

示例2: postfixEval

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import peek [as 别名]
def postfixEval(postfixExpr):
    pe = postfixExpr.split()
    s = Stack()
    for p in pe:
        if p in "0123456789":
            s.push(p)
        elif p in "+-*/":
            if not s.isEmpty():
                if not s.peek().isdigit():
                    return False
            else:
                return False
            op2 = int(s.pop())
            if not s.isEmpty():
                if not s.peek().isdigit():
                    return False
            else:
                return False
            op1 = int(s.pop())
            s.push(str(doMath(p,op1,op2)))
        print "unrecognized character"
        return 
    if s.size()==1:
        return s.peek().isdigit()
    else:
        return False
开发者ID:kickbean,项目名称:LeetCode,代码行数:28,代码来源:stack_postfixEvaluation.py

示例3: __to_postfix_tokens

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import peek [as 别名]
 def __to_postfix_tokens(self):
     postfix_expression = []
     operators = Stack()
     for token in self.tokens:
         if token not in "+-*/()":
             postfix_expression.append(token)
             continue
         if token == "(":
             operators.push(token)
         elif token == ")":
             while not operators.is_empty() and operators.peek() != "(":
                 postfix_expression.append(operators.pop())
             if not operators.is_empty():
                 operators.pop() # Pops the "("
         elif token in "+-":
             while not operators.is_empty() and operators.peek() in "+-*/":
                 postfix_expression.append(operators.pop())
             operators.push(token)
         elif token in "*/":
             while not operators.is_empty() and operators.peek() in "*/":
                 postfix_expression.append(operators.pop())
             operators.push(token)
     while not operators.is_empty():
         postfix_expression.append(operators.pop())
     return postfix_expression
开发者ID:bitbytejoy,项目名称:data-structures-and-algorithms,代码行数:27,代码来源:infix_to_postfix.py

示例4: infixToPostfix

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import peek [as 别名]
def infixToPostfix(infixString):
   opstack = Stack()
   infix = infixString.split()

   postfix = []

   operators = {}
   operators["+"] = 1
   operators["-"] = 1
   operators["*"] = 2
   operators["/"] = 2

   for token in infix:
      if token == '(':
         opstack.push(token)
      elif token == ')':
         backtoken = opstack.pop()
         while backtoken != '(':
            postfix.append(backtoken)
            backtoken = opstack.pop()
      elif token in operators.keys():
         while not opstack.isEmpty() and \
               operators.get(opstack.peek(), False) and \
               operators.get(token, False) and \
               operators[opstack.peek()] >= operators[token]:
            postfix.append(opstack.pop())
         opstack.push(token)
      else:
         postfix.append(token)

   while not opstack.isEmpty():
      postfix.append(opstack.pop())

   return " ".join(postfix)
开发者ID:agentreno,项目名称:pythonds,代码行数:36,代码来源:postfix.py

示例5: infixToPostfix

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import peek [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

示例6: __init__

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import peek [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

示例7: infix_to_postfix

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import peek [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

示例8: test_peek

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import peek [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

示例9: optsum

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import peek [as 别名]
def optsum(numbers):
	
	numstack = Stack()
	total = 0
	maxtotal = 0
	startmaxtotal = 0
	endmaxtotal = 0
	
	numstack.push(0)

	for index,value in enumerate(numbers):
		if value >= 0:
			numstack.push(numstack.pop() + value)
			total = numstack.peek()
			if total > maxtotal:
				endmaxtotal = index
				maxtotal = total
			# print maxtotal
		elif (numstack.peek() + value) > 0:
			numstack.push(numstack.pop() + value)
		else:
			numstack.pop()	
			numstack.push(0)
			startmaxtotal = index + 1

	return (startmaxtotal, maxtotal, endmaxtotal)
开发者ID:kaustubhkurve,项目名称:learn-python,代码行数:28,代码来源:stacksub.py

示例10: infixToPostfix

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import peek [as 别名]
def infixToPostfix(infixExpress):
    opstack=Stack() # to store operators,lower operators will be poped at first
    output=[]
    pre={'(':1,'+':2,'-':2,'^':3,'*':3,'/':3} # use int to hold precedence of operators,( holds the lowest
    if not isinstance(infixExpress,str):
        print ('Warning! expression should be str')
    length=len(infixExpress)
    index=0
    while index < length:
        character = infixExpress[index]
        if character.isdigit():
            output.append(character)
        elif character == '(':
            opstack.push(character)
        elif character in '+-*/^':
            while opstack.size() > 0 and pre[opstack.peek()] >= pre[character]: 
                output.append(opstack.pop())
            opstack.push(character) 
        elif character == ')':
            while opstack.peek() != '(':
                output.append(opstack.pop())    
            opstack.pop()
        index += 1
    
    while opstack.size() > 0: #字符串遍历完毕,若opstack中还有operator,就放入output
        output.append(opstack.pop())     
    
    return ' '.join(output)
开发者ID:ganlanshu,项目名称:datastructure,代码行数:30,代码来源:infix2Postfix.py

示例11: __init__

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

    def pop(self):
        top = self.top
        if self.top:
            self.top = self.top.nxt
        if top.val == self.minstack.peek():
            self.minstack.pop()
        return top.val

    def push(self,val):
        n = Node(val)
        n.nxt = self.top
        self.top = n
        if not self.minstack.peek() or val < self.minstack.peek():
            self.minstack.push(val)

    def peek(self):
        return self.top if self.top else None

    def min(self):
        return self.minstack.peek()
        
    def __str__(self):
        return str(self.top) if not self.top is None else ""

    def __repr__(self):
        return "StackMin("+str(self)+")"
开发者ID:malloc47,项目名称:snippets,代码行数:33,代码来源:cci.py

示例12: test_push

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import peek [as 别名]
    def test_push(self):
        test_stack = Stack()
        with self.assertRaises(ValueError):
            test_stack.peek()

        test_value = 22
        test_stack.push(test_value)
        self.assertEquals(test_value, test_stack.peek())
开发者ID:collin-mcgrath,项目名称:Data-Structure-Practice,代码行数:10,代码来源:test.py

示例13: test_push

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import peek [as 别名]
 def test_push(self):
     stack = Stack()
     stack.push("a")
     self.assertEquals(stack.peek(), "a")
     self.assertEquals(len(stack), 1)
     stack.push("b")
     self.assertEquals(stack.peek(), "b")
     self.assertEquals(len(stack), 2)
开发者ID:freephys,项目名称:crackingthecodinginterview,代码行数:10,代码来源:test_stack.py

示例14: Shunting

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import peek [as 别名]
class Shunting(object):
	def __init__(self, input):
		self.inputQueue = Queue()
		self.outputQueue = Queue()
		self.operatorStack = Stack()
		self.input = input
		self.operators = ["^", "*", "/", "%", "//", "+", "-", "(", ")"]
		
		self.processInput(self.input)
		print(self.inputQueue.peek())
		self.shunt()

	def processInput(self, input):
		holdItem = ""
		for i in range(0, len(input)):
			if input[i] in self.operators:
				if holdItem <> "":
					self.inputQueue.enqueue(holdItem)
				self.inputQueue.enqueue(input[i])
				holdItem = ""
			else:
				holdItem = holdItem + input[i]
		if holdItem <> "":
			self.inputQueue.enqueue(holdItem)
	
	def shunt(self):
		while self.inputQueue.peek() <> []:
			holdItem = ""
			holdItem = self.inputQueue.dequeue()
	
			if holdItem == "(":
				self.operatorStack.push(holdItem)
			elif holdItem == ")":
				temp = self.operatorStack.pop()
				while temp <> "(":
					self.outputQueue.enqueue(temp)
					temp = self.operatorStack.pop()
			elif holdItem in self.operators:
				if self.operatorStack.peek() == []:
					self.operatorStack.push(holdItem)
				else:
					while holdItem <> "":
						if self.operatorStack.peek() == []:
							self.operatorStack.push(holdItem)
							holdItem =""
						else:	
							result = compareOperators(holdItem, self.operatorStack.peek()[0])
							if result == 1:
								self.operatorStack.push(holdItem)
								holdItem = ""
							elif result == -1:
								self.outputQueue.enqueue(self.operatorStack.pop())

			else:
				self.outputQueue.enqueue(holdItem)

		while self.operatorStack.peek() <> []:
			self.outputQueue.enqueue(self.operatorStack.pop())
开发者ID:JasmineIslamNY,项目名称:Thinkful,代码行数:60,代码来源:shunting.py

示例15: main

# 需要导入模块: from stack import Stack [as 别名]
# 或者: from stack.Stack import peek [as 别名]
def main():
	s = Stack()
	s.isEmpty()
	s.push(1)
	s.push(2)
	s.push(5)
	s.peek()
	s.pop()
	s.print_list()
开发者ID:bxio,项目名称:microsoft-interview-practice,代码行数:11,代码来源:stack-test.py


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