I'm learning Python by implementing commonly used data structures. My primary language is Java, thus would like to know if I'm being Pythonic enough. Any means to better up will be appreciated.
class Node: def __init__(self, value=None, next=None): self.value = value self.next = next from node import Node class Stack: def __init__(self): self.top = None self.size = 0 def push(self, item): curr = Node(item) self.size += 1 if self.top is None: self.top = curr else: curr.next = self.top self.top = curr def peek(self): return self.top.value def pop(self): if self.top is None: raise Exception("Nothing to pop.") curr = self.top self.top = self.top.next self.size -= 1 return curr def __sizeof__(self): return self.size def is_empty(self): return self.size == 0; def __str__(self): curr = self.top while curr: print(curr.value, end=' ') curr = curr.next
The easiest way to create Stack that I found was this:
self.stack = 
raise Exception("nothing to pop")
raise Exception("Nothing to peek")
return len(self.stack) == 0
for x in self.stack.reverse(): #Reverse list, so when printing last pushed value is first and the oldest is printed last.
- What it does is when creating Stack Variable, it makes new list called
- When you push something to Stack, it is added at the end of list.
- When you pop something from Stack, it is taken away form list (method
pop() will not only return value from list, but also delete it)
- When you peek something from Stack, it returns last value on list without deleting it.
- When you want to check size of stack, it measures list size.
- When you want to use
__str__ you print all variables from list.
Reason for reversing list is because if I use
for x in stack: x will be equivalent to stack in first run, stack in second etc. However dont forget that stack is the oldest value placed in stack, and the newest is the value with the highest index in list.
A little bit more of explanation:
self.stack.pop(len(self.stack)-1) - This code will pop last value from list. It contains
-1 because length of stack is started from 1 while indexing is started from 0. Function
len() returns (in this case) length of list
if self.isEmpty(): raise Exception("Nothing to peek") - This code will run its function
isEmpty() from its own class, which returns Boolean value (perfectly for our if statement).
self.stack[len(self.stack)-1] while using list you will use list name (in this case stack) and then index you want to access, e.g. stack (will return second value in list, dont forget about 0-indexing).