Logo Manvith Reddy Dayam
Problem Solving with Python

Problem Solving with Python

May 1, 2024
Table of Contents

My experience

This was an amazing course and it improved my ability to solve problems using different data structures and algorithms. The homeworks were very challenging and long. Throught the course we worked with every single major data structure and used them to do many tasks.

I wish I could share all of them here but I think that is not allowed. Contact me and i’ll send you to the git repo.

Anyway, here’s a summary of something I enjoyed learning in this class.

Dijkstra’s Algorithm

Dijkstra’s Algorithm is an algorithm used to find the shortest path between nodes in a graph.

Dijkstra's Algorithm in Python
import heapq
 
def dijkstra(graph, start):
    # Create a priority queue
    pq = []
    # Push the starting node with distance 0
    heapq.heappush(pq, (0, start))
    # Distance dictionary (stores shortest distances to each node)
    distances = {node: float('infinity') for node in graph}
    # Distance to the start node is 0
    distances[start] = 0
 
    while pq:
        # Get the node with the smallest distance
        current_distance, current_node = heapq.heappop(pq)
 
        # If the current distance is greater than the recorded distance, skip
        if current_distance > distances[current_node]:
            continue
 
        # Check neighbors of the current node
        for neighbor, weight in graph[current_node]:
            distance = current_distance + weight
 
            # Only consider this new path if it's better
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                heapq.heappush(pq, (distance, neighbor))
 
    return distances
 
# Example usage:
graph = {
    'A': [('B', 1), ('C', 4)],
    'B': [('A', 1), ('C', 2), ('D', 5)],
    'C': [('A', 4), ('B', 2), ('D', 1)],
    'D': [('B', 5), ('C', 1)]
}
 
start_node = 'A'
distances = dijkstra(graph, start_node)
 
print("Shortest distances from node A:", distances)

stack to queue

Here’s another cool thing

stack to queue
from lab6.queue import *
from lab6.stack import *
 
def stackReversePublicMethods(stk: Stack):
    q = Queue()
    s = Stack()
    reverse = Stack()
 
    if stk.peek() == None:
        return None
 
    while not stk.is_empty():
        x = stk.peek()
        q.enqueue(x)
        
        reverse.push(x)
        stk.pop()
 
    while not q.is_empty():
        s.push(q.peek())
        q.dequeue()
 
    while not s.is_empty():
        stk.push(s.peek())
        s.pop()
    # print(reverse)
    return reverse, stk
 
s1=Stack()
s1.push("A")
s1.push("B")
s1.push("C")
 
reverse_stack, original_stack = stackReversePublicMethods(s1)
print(reverse_stack)  
print(original_stack)