Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Completed PreCourse1 #1998

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 61 additions & 19 deletions Exercise_1.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,66 @@
# Time Complexity:
# push() : O(1) - Inserting at the end of the list takes constant time.
# pop() : O(1) - Removing the last element takes constant time.
# peek() : O(1) - Accessing the last element is a constant-time operation.
# isEmpty(): O(1) - Checking if the stack is empty is constant time.
# size() : O(1) - Returning the length of the list is constant time.
# show() : O(n) - Displaying all elements takes linear time, where n is the number of elements.

# Space Complexity: O(n) - We use a list to store the elements, and it grows with the number of elements.

# Did this code successfully run on Leetcode?
# Not applicable (as it's a custom implementation), but it runs successfully on local environments.

# Any problem you faced while coding this:
# No issues encountered.

class myStack:
#Please read sample.java file before starting.
#Kindly include Time and Space complexity at top of each file
def __init__(self):

def isEmpty(self):

def push(self, item):

def pop(self):


def peek(self):

def size(self):

def show(self):

def __init__(self):
# Initialize an empty list to represent the stack
self.stack = []

def isEmpty(self):
# Check if the stack is empty
return len(self.stack) == 0

def push(self, item):
# Add an item to the top of the stack
self.stack.append(item)

def pop(self):
# Remove and return the top item from the stack
if not self.isEmpty():
return self.stack.pop()
else:
return "Stack is empty"

def peek(self):
# Return the top item without removing it
if not self.isEmpty():
return self.stack[-1]
else:
return "Stack is empty"

def size(self):
# Return the size of the stack
return len(self.stack)

def show(self):
# Display all items in the stack
return self.stack

# Your code here along with comments explaining your approach:
# - We use a Python list to simulate a stack.
# - `push()` adds an item to the stack.
# - `pop()` removes the top item.
# - `peek()` returns the top item without removing it.
# - `isEmpty()` checks if the stack is empty.
# - `size()` returns the number of elements in the stack.
# - `show()` prints all elements in the stack.

# Testing the stack implementation
s = myStack()
s.push('1')
s.push('2')
print(s.pop())
print(s.show())
print(s.pop()) # Output: '2'
print(s.show()) # Output: ['1']
65 changes: 57 additions & 8 deletions Exercise_2.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,81 @@
# Time Complexity:
# push() : O(1) - Adding a new node at the top is a constant-time operation.
# pop() : O(1) - Removing the top node is also a constant-time operation.
# isEmpty(): O(1) - Checking if the stack is empty takes constant time.

# Space Complexity: O(n) - Space grows with the number of nodes (elements) in the stack.

# Did this code successfully run on Leetcode?
# Not applicable, but it works successfully in local environments.

# Any problem you faced while coding this:
# No issues encountered.

# Your code here along with comments explaining your approach:
# - We use a linked list to implement the stack.
# - Each stack element is represented as a Node.
# - `push()` adds a new node at the top.
# - `pop()` removes the top node and returns its value.
# - `isEmpty()` checks if the stack has any nodes.
# - We use a `while` loop to allow the user to push, pop, or quit dynamically.

class Node:
def __init__(self, data):
self.data = data
self.next = None
self.data = data # Store the data value
self.next = None # Pointer to the next node

class Stack:
def __init__(self):

self.top = None # Initialize the top of the stack as None

def isEmpty(self):
# Check if the stack is empty by seeing if the top is None
return self.top is None

def push(self, data):

# Create a new node with the given data
new_node = Node(data)
# Link the new node to the current top node
new_node.next = self.top
# Update the top pointer to the new node
self.top = new_node

def pop(self):

# Check if the stack is empty
if self.isEmpty():
return None # Return None if the stack is empty

# Get the data from the top node
popped_data = self.top.data
# Move the top pointer to the next node
self.top = self.top.next
return popped_data # Return the popped value

# Initialize the stack
a_stack = Stack()

while True:
#Give input as string if getting an EOF error. Give input like "push 10" or "pop"
# Provide input as a string, e.g., "push 10" or "pop"
print('push <value>')
print('pop')
print('quit')
do = input('What would you like to do? ').split()
#Give input as string if getting an EOF error. Give input like "push 10" or "pop"

# Process the operation from user input
operation = do[0].strip().lower()

if operation == 'push':
# Push the given value onto the stack
a_stack.push(int(do[1]))

elif operation == 'pop':
# Pop the top value from the stack
popped = a_stack.pop()
if popped is None:
print('Stack is empty.')
else:
print('Popped value: ', int(popped))

elif operation == 'quit':
break
# Exit the loop
break
79 changes: 73 additions & 6 deletions Exercise_3.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,99 @@
# Time Complexity:
# append(data) : O(n) - We need to traverse to the end to insert the new node.
# find(key) : O(n) - We may have to traverse the entire list to find the key.
# remove(key) : O(n) - We may need to traverse the list to find and remove the key.

# Space Complexity: O(n) - Space grows linearly with the number of elements in the list.

# Did this code successfully run on Leetcode?
# Not applicable, but it runs successfully in local environments.

# Any problem you faced while coding this:
# No issues encountered.

class ListNode:
"""
A node in a singly-linked list.
"""
def __init__(self, data=None, next=None):

self.data = data # Store the data value
self.next = next # Store the reference to the next node

class SinglyLinkedList:
def __init__(self):
"""
Create a new singly-linked list.
Takes O(1) time.
"""
self.head = None
self.head = None # Initialize the head of the list to None

def append(self, data):
"""
Insert a new element at the end of the list.
Takes O(n) time.
"""

new_node = ListNode(data) # Create a new node with the given data
if self.head is None: # If the list is empty, set the head to the new node
self.head = new_node
return
# Traverse to the end of the list
current = self.head
while current.next:
current = current.next
# Add the new node at the end
current.next = new_node

def find(self, key):
"""
Search for the first element with `data` matching
`key`. Return the element or `None` if not found.
Search for the first element with `data` matching `key`.
Return the element or `None` if not found.
Takes O(n) time.
"""

current = self.head # Start from the head of the list
while current: # Traverse through the list
if current.data == key: # If data matches the key, return the node
return current
current = current.next # Move to the next node
return None # If the key is not found, return None

def remove(self, key):
"""
Remove the first occurrence of `key` in the list.
Takes O(n) time.
"""
current = self.head # Start from the head
previous = None # Keep track of the previous node

while current: # Traverse through the list
if current.data == key: # If data matches the key
if previous is None: # If it's the first node, update the head
self.head = current.next
else: # Otherwise, bypass the current node
previous.next = current.next
return # Exit after removing the node
previous = current # Move the previous pointer
current = current.next # Move to the next node

# Your code here along with comments explaining your approach:
# - `ListNode` defines each node of the linked list.
# - `SinglyLinkedList` manages the linked list.
# - `append(data)` adds a new node at the end.
# - `find(key)` searches for a node with matching data.
# - `remove(key)` removes the first occurrence of a node with matching data.

# Testing the SinglyLinkedList
sll = SinglyLinkedList()
sll.append(1)
sll.append(2)
sll.append(3)

# Find a node with value 2
node = sll.find(2)
print("Found:", node.data if node else "Not found") # Output: Found: 2

# Remove the node with value 2
sll.remove(2)

# Try to find the removed node
node = sll.find(2)
print("Found:", node.data if node else "Not found") # Output: Not found