25 KiB
25 KiB
In [9]:
# implementation of Node abstraction
class Node:
def __init__(self):
self.item = None # an item
self.next = None # a nodeIn [50]:
# initialize 3 nodes
first = Node()
second = Node()
third = Node()
# add content to the node
first.item = "to" # first node
second.item = "be" # second node
third.item = "or" # third node
# building the linked list
first.next = second
second.next = third
# iterate through this linked list and print the items
node = first
while node is not None:
print(node.item)
node = node.next
del node # delete the temporary nodeto be or
In [3]:
from typing import TypeVar
Item = TypeVar('Item') # don't worry about this, it makes code more readable
class Bag:
# define the constructor with 2 private attributes
def __init__(self) -> None:
self.__N = 0 # number of items - private
self.__first = None # point to first item in the bag - private
# add an item to bag
def add(self, item: Item) -> None:
oldFirst = self.__first
self.__first = self.Node() # create a new node
self.__first.item = item # add content to that node
self.__first.next = oldFirst # create a reference to next node
self.__N += 1 # increment the size of bag by 1
# nested class Node inside class Bag
class Node:
def __init__(self) -> None:
self.item = None
self.next = None
# method to check if bag is empty
def isEmpty(self) -> bool:
return self.__N == 0
# method to return the size of bag
def __len__(self) -> int:
return self.__N
# print the content of the bag
def __str__(self) -> str:
output_str = "["
self.__iter_node = self.__first
while True:
if self.__iter_node is not None:
output_str += f'{self.__iter_node.item}'
self.__iter_node = self.__iter_node.next
if self.__iter_node is not None:
output_str += ','
else:
break
output_str += ']'
return output_str
# The 2 methods below make the objects iterable
def __iter__(self):
self.__iter_node = self.__first
return self
def __next__(self):
if self.__iter_node is not None:
x = self.__iter_node.item
self.__iter_node = self.__iter_node.next
return x
else:
raise StopIteration
In [52]:
# create a variable of type Bag
bag = Bag()
print(f'The bag after initialization is {bag}')
# check if the bag is empty
print(f"bag is empty: {bag.isEmpty()} \n")
# let's add some items to this bag. Items could be of any data type
bag.add("University of Arkansas")
bag.add(1871)
bag.add("Fayetteville")
# print the content of bag
print(f"The size of the bag after adding is {len(bag)}") # thanks to __len__()
print('The items in the bag after adding are')
print(bag) # thanks to __str__()
# iterate through the bags and print each item
print("\nIterate through this bag")
for item in bag: # thanks to __iter__ and __next__
print(item, end=' ')The bag after initialization is [] bag is empty: True The size of the bag after adding is 3 The items in the bag after adding are [Fayetteville,1871,University of Arkansas] Iterate through this bag Fayetteville 1871 University of Arkansas
In [21]:
# Write class definition of queue below this line
class Queue():
items: list[Item] = []
def __init__(self) -> None:
pass
def enqueue(self, item: Item) -> None:
self.items.append(item)
def dequeue(self) -> Item:
return self.items.pop(0)
def isEmpty(self) -> bool:
return not bool(self.items)
def peek(self) -> Item | None:
return self.items[0] if len(self) > 0 else None
def __len__(self) -> int:
return len(self.items)
def __str__(self) -> str:
return str(self.items)
In [22]:
# initializing queue
queue = Queue()
print(f'The queue after initialization is {queue}')
assert(queue.isEmpty() == True) # check if isEmpty works properly
# add the items to queue
for i in range(5):
queue.enqueue(i)
print(f'The queue after enqueue is {queue}')
assert(queue.isEmpty() == False) # check if isEmpty works properly
assert(len(queue) == 5) # check if __len__ works properly
# Peek at the front item
front_item = queue.peek()
assert(front_item == 0) #check if peek is working properlyThe queue after initialization is [] The queue after enqueue is [0, 1, 2, 3, 4]
In [ ]:
# dequeue the queue
print("Dequeue the queue")
while len(queue) > 0:
item = queue.dequeue()
print(f'item dequeued from queue: {item}')
print(f'queue: {queue}')
print(f'length of queue: {len(queue)}')
assert(queue.isEmpty() == True)
# enqueue the queue
queue.enqueue(5)
print(f"\nQueue after enqueue: {queue}")
print(f"Length of queue: {len(queue)}")In [17]:
# Write class definition of stack below this line
class Stack():
items: list[Item] = []
def __init__(self) -> None:
pass
def push(self, item: Item) -> None:
self.items.append(item)
def pop(self) -> Item:
return self.items.pop()
def isEmpty(self) -> bool:
return not bool(self.items)
def peek(self) -> Item:
return self.items[-1]
def __len__(self) -> int:
return len(self.items)
In [18]:
# initializing stack
stack = Stack()
print(f'The stack after initialization is {stack}')
assert(stack.isEmpty() == True) # check if isEmpty works properly
# add the items to stack
for i in range(5):
stack.push(i)
print(f'The stack after push is {stack}')
assert(stack.isEmpty() == False) # check if isEmpty works properly
assert(len(stack) == 5) # check if __len__ works properly
#check if peek is working properly
top_item = stack.peek()
assert(top_item==4)The stack after initialization is <__main__.Stack object at 0x000001D262283450> The stack after push is <__main__.Stack object at 0x000001D262283450>
In [19]:
# pop the stack
print("Pop the stack")
while len(stack) > 0:
item = stack.pop()
print(f'item dequeued from stack: {item}')
print(f'stack: {stack}')
print(f'length of stack: {len(stack)}')
assert(stack.isEmpty() == True)
# enqueue the queue
stack.push(5)
print(f"\nstack after push: {stack}")
print(f"length of stack: {len(stack)}")Pop the stack item dequeued from stack: 4 stack: <__main__.Stack object at 0x000001D262283450> length of stack: 4 item dequeued from stack: 3 stack: <__main__.Stack object at 0x000001D262283450> length of stack: 3 item dequeued from stack: 2 stack: <__main__.Stack object at 0x000001D262283450> length of stack: 2 item dequeued from stack: 1 stack: <__main__.Stack object at 0x000001D262283450> length of stack: 1 item dequeued from stack: 0 stack: <__main__.Stack object at 0x000001D262283450> length of stack: 0 stack after push: <__main__.Stack object at 0x000001D262283450> length of stack: 1
In [8]:
class BrowserHistory:
def __init__(self, homepage: str):
self.current_page = homepage
# create a backward stack
# create a forward stack
def visit(self, url: str) -> None:
# function to visit a new page, updating the history accordingly.
pass # remove this
def back(self, steps: int) -> str:
# function to oves back a specified number of steps in the browsing history.
pass
def forward(self, steps: int) -> str:
# function to moves forward a specified number of steps in the browsing history.
pass
def current(self) -> str:
# function to get URL of the current active page
pass
In [33]:
history = BrowserHistory("uark-aicv.github.io")
history.visit("uark-aicv.github.io/team")
history.visit("uark-aicv.github.io/research")
history.visit("uark-aicv.github.io/publications")
history.visit("uark-aicv.github.io/contact")
assert(history.current()=='uark-aicv.github.io/contact')
Browser initialized with homepage: uark-aicv.github.io
In [34]:
history.back(2)
assert(history.current()=='uark-aicv.github.io/research')In [ ]:
history.forward(1)
assert(history.current()=='uark-aicv.github.io/publications')