Skip to content
Snippets Groups Projects
Commit 8c03f40d authored by Angy Wallot's avatar Angy Wallot
Browse files

Upload New File

parent 7e83250c
No related branches found
No related tags found
No related merge requests found
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
:mod:`stack` module
:author: `FIL - Faculté des Sciences et Technologies -
Univ. Lille <http://portail.fil.univ-lille1.fr>`_
:date: 2015, september
:last revision: 2017, october
A module for stack data structure.
:Provides:
* class ApStack
and methods
* `push`
* `pop`
* `top`
* `is_empty`
:Examples:
"""
from typing import TypeVar
T = TypeVar('T')
class ApStackEmptyError(Exception):
"""
Exception for empty stacks
"""
def __init__(self, msg):
self.message = msg
class ApStack():
"""
$$$ stak = ApStack()
$$$ stak.is_empty()
True
$$$ stak.push(1)
$$$ stak.is_empty()
False
$$$ stak.push(2)
$$$ stak.top()
2
$$$ stak.pop()
2
$$$ stak.top()
1
$$$ stak.pop()
1
$$$ stak.is_empty()
True
$$e stak.pop()
ApStackEmptyError
"""
def __init__(self):
"""
build a new empty stack
précondition : none
"""
self.__content = []
def push(self, el: T):
"""
add el on top of the stack.
précondition : none
"""
self.__content.append(el)
def pop(self) -> T:
"""
return the element on top of self
Side effect: self contains an element less
précondition : self must be non empty
"""
if len(self.__content) == 0:
raise ApStackEmptyError('empty stack, nothing to pop')
return self.__content.pop()
def top(self) -> T:
"""
return the element on top of self without removing it
précondition : self must be non empty
"""
if len(self.__content) == 0:
raise ApStackEmptyError('empty stack, nothing to pop')
return self.__content[-1]
def is_empty(self) -> bool:
"""
return:
* ``True`` if s is empty
* ``False`` otherwise
précondition : none
"""
return self.__content == []
def __str__(self) -> str:
"""
return a stack representation
"""
mlen = 1
if not self.is_empty():
mlen = max(len(str(el)) for el in self.__content)
res = []
for el in self.__content:
pad = mlen - len(str(el))
left = pad // 2
right = pad - left
res.insert(0, "|" + " " * left + str(el) + " " * right + "|")
res.append("+" + "-" * mlen + "+")
return "\n".join(res)
def __len__(self) -> int:
"""
Return the stack length.
"""
return len(self.__content)
if (__name__ == '__main__'):
import apl1test
apl1test.testmod('apstack.py')
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment