Code Sharing — 9 Python Snippets

Slot 1 — Water Jug (BFS)

from collections import deque

def water_jug_bfs(capacity_a, capacity_b, target):
    visited = set()
    queue = deque([(0, 0, [])])

    while queue:
        a, b, path = queue.popleft()

        # If we reach the target, return the path including this step
        if a == target or b == target:
            return path + [(a, b)]

        if (a, b) in visited:
            continue
        visited.add((a, b))

        # ALL possible next states
        next_states = [
            (capacity_a, b),           # Fill jug A
            (a, capacity_b),           # Fill jug B
            (0, b),                    # Empty jug A
            (a, 0),                    # Empty jug B
            (max(0, a - (capacity_b - b)), min(b + a, capacity_b)),  # Pour A -> B
            (min(a + b, capacity_a), max(0, b - (capacity_a - a)))   # Pour B -> A
        ]

        for new_a, new_b in next_states:
            if (new_a, new_b) not in visited:
                queue.append((new_a, new_b, path + [(a, b)]))

    return None  # No solution found


# Test
jug_capacity_a = 4
jug_capacity_b = 3
target_amount = 2

solution_path = water_jug_bfs(jug_capacity_a, jug_capacity_b, target_amount)
if solution_path:
    print("Solution path:")
    for step in solution_path:
        print(f"({step[0]},{step[1]})")
else:
    print("No solution found")
      

Slot 2 — Minimax

import math

def minimax(curDepth, nodeIndex, maxTurn, scores, targetDepth):
    if curDepth == targetDepth:
        return scores[nodeIndex]

    if maxTurn:
        return max(
            minimax(curDepth + 1, nodeIndex * 2, False, scores, targetDepth),
            minimax(curDepth + 1, nodeIndex * 2 + 1, False, scores, targetDepth)
        )
    else:
        return min(
            minimax(curDepth + 1, nodeIndex * 2, True, scores, targetDepth),
            minimax(curDepth + 1, nodeIndex * 2 + 1, True, scores, targetDepth)
        )

scores = [3, 5, 2, 9, 12, 5, 23, 23]
treeDepth = int(math.log(len(scores), 2))

print("The optimal value is: ", end="")
print(minimax(0, 0, True, scores, treeDepth))
      

Slot 3 — K-Means Clustering

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans

X, _ = make_blobs(n_samples=300, centers=4, random_state=42)

kmeans = KMeans(n_clusters=4)
kmeans.fit(X)

labels = kmeans.cluster_centers_

plt.scatter(X[:, 0], X[:, 1], c=kmeans.labels_, cmap='viridis', edgecolors='k')

plt.title('K-Means Clustering')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')

# Plot centroids
centroids = kmeans.cluster_centers_
plt.scatter(centroids[:, 0], centroids[:, 1], marker='x', s=200, color='red')

plt.show()
      

Slot 4 — Naive Bayes (example)

import numpy as nm
import matplotlib.pyplot as mtp
import pandas as pd

dataset = pd.read_csv('user_data.csv')
x = dataset.iloc[:, [2, 3]].values
y = dataset.iloc[:, 4].values

print(dataset)

from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.25, random_state = 0)

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
x_train = sc.fit_transform(x_train)
x_test = sc.transform(x_test)

from sklearn.naive_bayes import GaussianNB
classifier = GaussianNB()
classifier.fit(x_train, y_train)

y_pred = classifier.predict(x_test)

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
print(cm)
      

Slot 5 — Decision Tree + Metrics

import numpy as nm
import matplotlib.pyplot as mtp
import pandas as pd

data_set = pd.read_csv('user_data.csv')
x = data_set.iloc[:, [2, 3]].values
y = data_set.iloc[:, 4].values

from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=0)

from sklearn.preprocessing import StandardScaler
st = StandardScaler()
x_train = st.fit_transform(x_train)
x_test = st.transform(x_test)

from sklearn.tree import DecisionTreeClassifier
classifier = DecisionTreeClassifier(criterion="entropy", random_state=0)
classifier.fit(x_train, y_train)

y_pred = classifier.predict(x_test)

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
print(cm)

from sklearn.metrics import precision_score, recall_score, f1_score, accuracy_score

print("Precision: %f" % precision_score(y_test, y_pred))
print("Recall: %f" % recall_score(y_test, y_pred))
print("F1 Score: %f" % f1_score(y_test, y_pred))
print("Accuracy: %f" % accuracy_score(y_test, y_pred))

import matplotlib.pyplot as plt
from sklearn.metrics import PrecisionRecallDisplay

PrecisionRecallDisplay.from_estimator(classifier, x_test, y_test)
plt.show()
      

Slot 6 — N-Queens

N=4
ld=[0]*30
rd=[0]*30
cl=[0]*30

def printSolution(board):
    for i in range(N):
        for j in range(N):
            print("1" if board[i][j]==1 else "0", end=" ")
        print()

def solveNQUtil(board, col):
    if col==N:
        return True

    for i in range(N):
        if ((ld[i-col+N-1]!=1) and (rd[i+col]!=1) and (cl[i]!=1)):
            board[i][col]=1
            ld[i-col+N-1]=rd[i+col]=cl[i]=1

            if solveNQUtil(board, col+1):
                return True

            board[i][col]=0
            ld[i-col+N-1]=rd[i+col]=cl[i]=0

    return False

def solveNQ():
    board=[[0 for _ in range(N)]for _ in range(N)]
    if not solveNQUtil(board, 0):
        print("Solution does not exist")
        return False
    printSolution(board)
    return True

if __name__ == "__main__":
    solveNQ()
      

Slot 7 — Image Processing (PIL + OpenCV)

from PIL import Image,ImageFilter
import os,sys
import cv2
from matplotlib import pyplot as plt
im=Image.open("img1.png")
im=im.rotate(90)
im.show()
size=(128,128)
im1=im.resize(size)
im1.save("img128.png")

blurImage=im.filter(ImageFilter.BLUR)
blurImage.show()
blurImage.save("Bluring.png")

img=cv2.imread('img1.png',0)
cv2.imshow('GrayscaleImage',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
img=cv2.imread('img1.png',cv2.IMREAD_GRAYSCALE)
edges=cv2.Canny(img,100,200)
plt.subplot(121),plt.imshow(img,cmap='gray')
plt.title('Original Image'),plt.xticks([]),plt.yticks([])
plt.subplot(122),plt.imshow(edges,cmap='gray')
plt.title('Edge Image'),plt.xticks([]),plt.yticks([])
plt.show()

ret,thresh1=cv2.threshold(img,122,25,cv2.THRESH_BINARY)
plt.subplot(122),plt.imshow(thresh1,cmap='gray')
plt.title('Segmented Image'),plt.xticks([]),plt.yticks([])
plt.show()
      

Slot 8 — NLP: Tokenize / Stemming

import nltk
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer

# Download (first time only)
# nltk.download('punkt')
# nltk.download('stopwords')

text = "Tokenizing is an important concept under NLP. Happy learning"

# Sentence Tokenization
print("Sentence tokens:", sent_tokenize(text))

# Word Tokenization
print("Word tokens:", word_tokenize(text))

# Stopwords Removal
stop_words = set(stopwords.words("english"))
words = text.split()

print("Content without stopwords:")
for w in words:
    if w.lower() not in stop_words:
        print(w)

# Stemming
ps = PorterStemmer()
words = ["Program", "Programs", "Programmer", "Programming", "Programmers"]

print("\nStemming Output:")
for w in words:
    print(w, ":", ps.stem(w))
      

Slot 9 — NLP: POS / Chunk / NER


import nltk
from textblob import TextBlob

sentence = "I am learning NLP in Python"
text_blob = TextBlob(sentence)
pos_tags = text_blob.tags
print(pos_tags)

import re
test_str = "R A F First Grade College"
print("The original string is: " + str(test_str))
k = 5
chnk_len = len(test_str)

res = re.findall(r"[A-Z][a-z]*", test_str)
print("The chunked list: " + str(res))

import spacy
nlp = spacy.load("en_core_web_sm")

ner_categories = ["PERSON", "GPE", "FAC"]

text = "Sir M Visvesvaraya was responsible for the construction of the Krishna Raja Sagara Dam in Mysore"
doc = nlp(text)

entities = []
for ent in doc.ents:
    if ent.label_ in ner_categories:
        entities.append((ent.text, ent.label_))

for entity, category in entities:
    print(f"{entity}:{category}")