Hoşgeldin Misafir

Python'da Stack

MiRaT

13 Kas 2017
2,077 Mesaj

Aktiflik

Seviye

Deneyim

TIM / GÖREV:
Kod:
#!/usr/bin/env python2
#-*- coding: utf-8 -*-
#
#

"https://gist.github.com/laszlokuehl/ce69f6abc3e4e2f1e94f2adf2196bee0"

__author__ = '@laszlokuehl'

class Stack:
    def __init__(self, maxSize):
        self.maxSize = int(maxSize)
        self.__data = []

    def __str__(self):
        return str(self.__data)

    def __repr__(self):
        return self.__str__()

    def __error(self, msg):
        raise Exception(msg)

    def isEmpty(self):
        return len(self.__data) == 0

    def isFull(self):
        return len(self.__data) == self.maxSize

    def push(self, item):
        return self.__data.append(item) if self.isFull() != True else self.__error('Stack is full')

    def pop(self):
        return self.__data.pop(-1) if self.isEmpty() != True else self.__error('Stack is empty')

    def peek(self):
        return self.__data[-1] if self.isEmpty() != True else self.__error('Stack is empty')

    def search(self, item):
        return self.__data.index(item) if self.isEmpty() != True else self.__error('Stack is empty')

-Aşağıda kullanımı bulunuyor.--


Kod:
>>> 
>>> stack = Stack(20)
>>> 
>>> stack.isEmpty()
True
>>> 
>>> [stack.push(x) for x in range(20)]
[None] * 20
>>> 
>>> stack.isEmpty()
False
>>> 
>>> stack.isFull()
True
>>> 
>>> stack.peek()
19
>>> 
>>> stack.search(8)
8
>>> 
>>> [stack.pop() for x in range(20)]
[19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> 
>>> stack.push('test')
>>> stack.push('test2')
>>> stack.push('test3')
>>> 
>>> stack.search('test')
0
>>> 
>>> stack.search('test3')
2
>>>