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")
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()
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}")