Skip to content

Instantly share code, notes, and snippets.

@faif
Last active October 11, 2015 01:48
Show Gist options
  • Save faif/3784185 to your computer and use it in GitHub Desktop.
Save faif/3784185 to your computer and use it in GitHub Desktop.
stack
from stack import stack
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
if __name__ == '__main__':
s1 = stack()
print(sort(s1))
[s1.push(i) for i in (-10.5, 48.3, -7.1, 19.23, -8, -10.5)]
s2 = sort(s1)
print(s2)
class stack:
def __init__(self):
self._contents = list()
def __str__(self):
return '{}'.format(self._contents[::-1])
def __len__(self):
return len(self._contents)
def push(self, item):
self._contents.append(item)
def pop(self):
top = None
try:
top = self._contents.pop()
except Exception:
print('Empty stack!')
return top
def peek(self):
return self._contents[-1] if len(self) else None
if __name__ == '__main__':
s1 = stack()
print(s1)
print(len(s1))
[s1.push(x) for x in range(3)]
print(s1)
[print('pop:', s1.pop()) for _ in range(len(s1))]
x = s1.pop()
print('x:', x)
print('peek', s1.peek())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment