2.Data preprocessing import pandas as pd import numpy as np df=pd.read_csv("C:/Users/yasha/OneDrive/Desktop/airline.csv") df.head() Country Airline passengers carried Year 0 United States 666,153,000 2021 1 China 440,301,216 2021 2 Russia 96,851,770 2 021 3 India 83,964,797 2021 4 Ireland 74,065,210 2021 df.head(10) Country Airline passengers carried Year 0 United States 666,153,000 2021 1 China 440,301,216 2021 2 Russia 96,851,770 2021 3 India 83,964,797 2021 4 Ireland 74,065,210 2021 5 Turke y 69,065,870 2021 6 Brazil 61,896,520 2021 7 Mexico 54,217,880 2021 8 Japan 45,410,150 2021 9 Spain 43,440,480 2021 df.tail() Country Airline passengers carried Year 172 Malawi 1,290 2021 173 Benin 900 2016 174 Estonia 860 2019 175 North Korea 52 0 2021 Country Airline passengers carried Year 176 Monaco 320 2017 df.tail(6) Country Airline passengers carried Year 171 Lesotho 1,300 1999 172 Malawi 1,290 2021 173 Benin 900 2016 174 Estonia 860 2019 175 North Korea 520 2021 176 Monaco 320 2017 df.isnull().sum() Country 0 Airline passengers carried 0 Year 0 dtype: int64 df.info() <class 'pandas.core.frame.DataFrame'> RangeIndex: 177 entries, 0 to 176 Data columns (total 3 columns): # Column Non - Null Count Dt ype --- ------ -------------- ----- 0 Country 177 non - null object 1 Airline passengers carried 177 non - null object 2 Year 177 non - null int64 dtypes: int64(1), object(2) memory usage: 4.3+ KB df.columns Index(['Country', 'Airline passengers carried', 'Year'], dtype='object') df.dtypes Country object Airline passengers carried object Year int64 dtype: object df.shape (1 77, 3) df.describe <bound method NDFrame.describe of Country Airline passengers carried Year 0 United States 666,153,000 2021 1 China 440,301,216 2021 2 Russia 96,851,770 2021 3 India 83,964,797 2021 4 Ireland 74,065,210 2021 .. ... ... ... 172 Malawi 1,290 2021 173 Benin 900 2016 174 Estonia 860 2019 175 North Korea 520 2021 176 Monaco 320 2017 [177 rows x 3 columns]> df.isnull() Country Airline passengers carried Year 0 False Fal se False 1 False False False 2 False False False 3 False False False 4 False False False ... ... ... ... 172 False False False 173 False False False 174 False False False 175 False False False 176 False False False 177 rows × 3 columns 4.BFS,DFS ,UCS Bfs maze from collections import deque directions=[(0,1),(1,0),(0, - 1),( - 1,0)] def bfs_maze(maze,start,goal): rows,cols=len(maze),len(maze[0]) queue=deque([start]) visited=set([start]) parent={start:None} while queue: r,c=qu eue.popleft() if (r,c)==goal: break for dr,dc in directions: nr,nc=r+dr,c+dc if 0 <= nr < rows and 0 <= nc < cols: if maze[nr][nc]==0 and (nr,nc) not in visited: visite d.add((nr,nc)) queue.append((nr,nc)) parent[(nr,nc)]=(r,c) path=[] current=goal while current: path.append(current) current=parent.get(current) path.reverse() return path maze=[ [0,1,0,0], [0,0,0,1], [1,0,1,0], [0,0,0,0] ] start=(0,0) goal=(3,3) print("shortest path:", bfs_maze(maze,start,goal)) shortest path: [(0, 0), (1, 0), (1, 1), (2, 1), (3, 1), (3, 2), (3, 3)] dfs maze from collections im port deque directions=[(0,1),(1,0),(0, - 1),( - 1,0)] def dfs_maze(maze,start,goal): rows,cols=len(maze),len(maze[0]) visited=[[False]*cols for _ in range(rows)] path=[] directions =[( - 1,0),(1,0),(0, - 1),(0,1)] def dfs(r,c): if r<0 or r >= rows or c<0 or c>= cols: return False if maze[r][c] == 1 or visited [r][c]: return False visited[r][c] = True path.append((r,c)) if(r,c) == goal: return True for dr,dc in d irections: if dfs(r+dr,c+dc): return True path.pop() return False dfs(start[0],start[1]) return path maze=[ [0,1,0,0,0], [0,1,0,1,0], [0,0,0,1,0], [1,1,0,0,0] ] start=(0,0) goal=( 3,4) path=dfs_maze(maze,start,goal) print("DFS path:",path) DFS path: [(0, 0), (1, 0), (2, 0), (2, 1), (2, 2), (1, 2), (0, 2), (0, 3), (0, 4), (1, 4), (2, 4), (3, 4)] Bfs grid from collections import deque directions=[(0,1),(1,0),(0, - 1),( - 1,0)] def bfs_grid(grid,start,goal): rows,cols=len(grid),len(grid[0]) queue=deque([start]) visited=set([start]) parent={start:None} while queue: r,c=queue.popleft() if (r,c)==goal: break for dr,dc in direct ions: nr,nc=r+dr,c+dc if 0 <= nr < rows and 0 <= nc < cols: if grid[nr][nc]==0 and (nr,nc) not in visited: visited.add((nr,nc)) queue.append((nr,nc)) parent [(nr,nc)]=(r,c) if goal not in parent: return None path=[] current=goal while current: path.append(current) current=parent.get(current) path.reverse() return path grid=[ [0,0,1,0], [1,0,1,0], [0,0,0,0], [0,1,1,0] ] start=(0,0) goal=(3,3) print("shortest path:", bfs_grid(grid,start,goal)) shortest path: [(0, 0), (0, 1), (1, 1), (2, 1), (2, 2), (2, 3), (3, 3)] dfs grid from collections import deque directions=[(0,1),(1,0),( 0, - 1),( - 1,0)] def dfs_grid(grid,start,goal): rows,cols=len(grid),len(grid[0]) visited=[[False]*cols for _ in range(rows)] path=[] directions =[( - 1,0),(1,0),(0, - 1),(0,1)] def dfs(r,c): if r<0 or r >= rows or c<0 or c>= cols: return False if grid[r][c] == 1 or visited [r][c]: return False visited[r][c] = True path.append((r,c)) if(r,c) == goal: return True for dr,dc in directions: if dfs(r+dr,c +dc): return True path.pop() return False dfs(start[0],start[1]) return path grid=[ [0,1,0,0], [0,0,0,1], [0,0,0,1,0], [1,1,0,0,0] ] start=(0,0) goal=(3,4) path=dfs_maze(maze,start,goal) prin t("DFS path:",path) Use search import heapq def ucs_search(graph,start,goal): pq=[(0,start,[start])] visited=set() while pq: cost,node,path=heapq.heappop(pq) if node==goal: return cost,path if no de in visited: continue visited.add(node) for neighbor,edge_cost in graph.get(node,[]): if neighbor not in visited: heapq.heappush(pq,(cost+edge_cost,neighbor,path+[neighbor])) return None Graph={ 'A':[('B',1),('C',4)], 'B':[('D',2),('E',5)], 'C':[('F',3)], 'D':[('G',1)], 'E':[('G',2)], 'F':[('G',5)], 'G':[] } cost,path=ucs_search(Graph,'A','G') print("cost:",cost) print("path:"," - >".join(path)) cost: 4 path: A - >B - >D - > G 5. greedy bfs and a star import heapq def heuristic(a,b): return abs(a[0] - b[0])+abs(a[1] - b[1]) def reconstruct_path(came_from,current): path=[current] while current in came_from: current=came_from[current] path.append(cu rrent) path.reverse() return path def greedy_best_first_search(grid,start,goal): rows,cols=len(grid),len(grid[0]) open_list=[] heapq.heappush(open_list,(heuristic(start,goal),start)) came_from={} visited=set() while open_lis t: _,current=heapq.heappop(open_list) if current==goal: return reconstruct_path(came_from,current) visited.add(current) x,y=current for dx,dy in [(1,0),( - 1,0),(0,1),(0, - 1)]: nx,ny=x+dx,y+dy if 0 <= nx < rows and 0 <= ny < cols: if grid[nx][ny]==1: continue neighbor=(nx,ny) if neighbor not in visited: came_from[neighbor]=current heapq.heappush(open_list,(heuristic(neighbor,goal),neighbo r)) return None def a_star(grid,start,goal): rows,cols=len(grid),len(grid[0]) open_list=[] heapq.heappush(open_list,(0,start)) came_from={} g_score={start:0} while open _list: _,current=heapq.heappop(open_list) if current==goal: return reconstruct_path(came_from,current) x,y=current for dx,dy in [(1,0),( - 1,0),(0,1),(0, - 1)]: nx,ny=x+dx,y+dy if 0 <= nx < ro ws and 0 <= ny < cols: if grid[nx][ny]==1: continue neighbor=(nx,ny) tentative_g=g_score[current]+1 if neighbor not in g_score or tentative_g < g_score[neighbor]: came_from[neighbor]=current g_score[neighbor]=tentative_g f=tentative_g+heuristic(neighbor,goal) heapq.heappush(open_list,(f,neighbor)) return None if __name__=="__main__": grid =[ [0,0,0,1,0], [1,0,1,0,0], [0,0,0,0,1], [0,1,1,0,0], [0,0,0,0,0] ] start=(0,0) goal=(4,4) print("greedy best_first_search path:",greedy_best_first_search(grid,start,goal)) print("A* path:",a_sta r(grid,start,goal)) greedy best_first_search path: [(0, 0), (0, 1), (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4)] A* path: [(0, 0), (0, 1), (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4)] 6.minimax and alpha beta import math from copy import deepcopy PLAYER_X="X" PLAYER_O="O" EMPTY="" def check_winner(board): lines=[] for i in range(3): lines.append(board[i]) lines.append([board[0][i],board[1][i],board[2][i]]) lines.append([board[0][0],board[1] [1],board[2][2]]) lines.append([board[0][2],board[1][1],board[2][0]]) if [PLAYER_X]*3 in lines: return 1 if [PLAYER_O]*3 in lines: return - 1 return 0 def is_full(board): return all(cell != EMPTY f or row in board for cell in row) def get_moves(board): return[(i,j) for i in range(3) for j in range(3) if board[i][j]==EMPTY] def minimax(board,depth,is_max,indent=""): score=check_winner(board) if score != 0 or is_full(board): print(f "{indent} leaf score: {score}") return score if is_max: best=math.inf print(f"{indent} MAX node") for (i,j) in get_moves(board): board[i][j]=PLAYER_X print(f"{indent} move X - > ({i},{j})") value=minimax(board,depth+1,False,indent+" ") board[i][j]=EMPTY best=max(best,value) print(f"{indent} MAX returns {best}") return best else: best=math.inf print(f"{indent} MIN node") for (i,j) in get_moves(board): board[i][j]=PLAYER_O print(f"{indent} move O - > ({i}{j})") value=minimax(board,depth+1,True,indent+" ") board[i][j]=EMPTY best=min(best,value) print(f"{inde nt} MIN returns {best}") return best def alphabeta(board,depth,alpha,beta,is_max,indent=" "): score=check_winner(board) if score != 0 or is_full(board): print(f"{indent} Max node(a={alpha},b={beta})") for (i,j) in get_moves( board): board[i][j]=PLAYER_X print(f"{indent} Move X - > ({i},{j})") value=alphabeta(board,depth+1,aplha,beta,False,indent+" ") board[i][j]=EMPTY best=max(best,value) alpha=max(alpha,bes t) if beta <= alpha: print(f"{indent} pruned") break print(f"{indent} MAX returns{best}") return best else: best=math.inf print(f"{indent} MIN node(a={alpha},b={beta})") for (i,j) in get_moves(board): board[i][j]=PLAYER_O print(f"{indent} move O - >({i},{j})") value=aplhabeta(board,depth+1,alpha,beta,True,indent+" ") board[i][j]=EMPTY best=min(best,value) beta=min(beta,best) if beta <= alpha: print(f"{indent} pruned") break print(f"{indent} MIN returns{best}") return best if __name__=="__main__": board=[ [EMPTY,EMPTY,EMPTY], [EMPTY,EMPTY,EMPTY], [EMPTY,EMPTY,EMPTY] ] print("=====MINIMAX SEARCH TREE =====") minimax(board,0,True) print(" \ n=====ALPHA - BETA SEARCH TREE =====") alphabeta(board,0,math.inf,math.inf,True) 7.map coloring def is_safe (region,color,assignment,adjacency_map): for neighbor in adjacency_map[region]: if neighbor in assignment and assignment[neighbor]== color: return False return True def map_coloring_backtracking(assignment,regions,colors,adjace ncy_map): if len(assignment)== len(region): return assignment unassigned =[ r for r in regions if r not in assignment][0] for color in colors: if is_safe(unassigned,color,assignment,adjacency_map): assignment[unass igned]=color result =map_coloring_backtracking(assignment,regions,colors,adja cency_map) if result: return result del assignment[unassigned] return None if __name__ =="__main__": region=["A", "B","C","D","E","F","G"] color=["Red","Green","Blue"] adjacency_map={ "A":["B","C"], "B":["A","C","D"], "C":["A","B","D","E"], "D":["B","C","E","F"], "E":["C","D","F"], "F":["D","E","G"], "G": ["F"] } solution=map_coloring_backtracking({},region,color,adjacency_map) if solution: print("Map Coloring Solution:") for region,color in solution.items(): print(f"Region{region}:{color}") else: print("N o solution found") Map Coloring Solution: RegionA:Red RegionB:Green RegionC:Blue RegionD:Red RegionE:Green RegionF:Blue RegionG:Red 8.unification algorithm and test with sample FOL expression for brother reation def is_variable(x): return isinstan ce(x, str) and x.islower() def is_constant(x): return isinstance(x, str) and x[0].isupper() def occurs_check(var, x, subs): if var == x: return True if is_variable(x) and x in subs: return occurs_check(var, subs[x], subs) if isinstance(x, tuple): return any(occurs_check(var, arg, subs) for arg in x) return False def substitute(x, subs): if is_variable(x) and x in subs: return substitute(subs[x], subs) if isinstance(x, tuple): return tupl e(substitute(arg, subs) for arg in x) return x def unify(x, y, subs=None): if subs is None: subs = {} x = substitute(x, subs) y = substitute(y, subs) if x == y: return subs if is_variable(x): if occurs_che ck(x, y, subs): return None subs[x] = y return subs if is_variable(y): if occurs_check(y, x, subs): return None subs[y] = x return subs if isinstance(x, tuple) and isinstance(y, tuple) : if len(x) != len(y) or x[0] != y[0]: return None for arg_x, arg_y in zip(x[1:], y[1:]): subs = unify(arg_x, arg_y, subs) if subs is None: return None return subs return None expr1 = ('brother', 'x', 'John') expr2 = ('brother', 'Bob', 'y') result = unify(expr1, expr2) print(result) {'x': 'Bob', 'y': 'John'} 9. chaining on academic advising knowledge base facts={ "GPA":8.2, "Credits":125, "Major":"CS", " Interest":"AI" } derived_facts=set() rules=[ (lambda f:f["GPA"] >= 8.0 and f["Credits"] >= 120,"Eligible_Honors"), (lambda f:f["GPA"] >= 6.5 and f["Credits"] >= 90,"Eligible_Internship"), (lambda f:f["Major"] == "CS" and f["Interest"]=="AI","AI _Electives"), (lambda f:"Eligible_Internship" in derived_facts,"Industry_Project"), (lambda f:"Eligible_Honors" in derived_facts,"Research_Project") ] def forward_chaining(): applied=True while applied: applied=False #for co ndition(facts) and conclusion in rules: for condition, conclusion in rules: if condition(facts) and conclusion not in derived_facts: derived_facts.add(conclusion) applied=True forward_chaining() print("D erived academic Advice: ") for fact in derived_facts: print("_",fact) facts={ "GPA":8.2, "Credits":125, "Major":"CS", "Interest":"AI" } def backward_chaining(goal): if goal == "Research_Project": r eturn backward_chaining("Eligible_Honors") if goal == "Eligible_Honors": return facts["GPA"] >= 8.0 and facts["Credits"] >= 120 if goal == "Industry_Project": return backward_chaining("Eligible_Internship") if goal == "Eligible_ Internship": return facts["GPA"] >= 6.5 and facts["Credits"] >= 90 return False goal="Research_Project" result=backward_chaining(goal) print(f"Is the student eligible for {goal}?:",result) output: Derived academic Advice: _ Research_Project _ AI_Electives _ Eligible_Honors _ Eligible_Internship _ Industry_Project Is the student eligible for Research_Project?: True 10.STRIPS style from collections import deque class Action: def __init__(self,name,preconds,add_effects,del_effects): self.name=name self.preconds=set(preconds) self.add_effects=set(add_effects) self.del_effects=set(del_effects) def is_applicable(self,state): return self.preconds.issubset(state) def apply(self,state): retur n self.preconds.issubset(state) def apply(self,state): new_state=set(state) new_state - = self.del_effects new_state |= self.add_effects return new_state def __repr__(self): return self.name def strips_planner (initial_state,goal_state,actions): frontier=deque() frontier.append((initial_state,[])) explored=set() while frontier: state,plan=frontier.popleft() if goal_state.issubset(state): return plan explored.ad d(frozenset(state)) for action in actions: if action.is_applicable(state): new_state=action.apply(state) fs=frozenset(new_state) if fs not in explored: frontier.append( (new_state,plan+[action])) return None actions=[ Action( "Move(room1,room2)", preconds={"at(robot,room1)"}, add_effects={"at(robot,room2)"}, del_effects={"at(robot,room1)"} ), Action( "Move(ro om1,room2)", preconds={"at(robot,room2)"}, add_effects={"at(robot,room1)"}, del_effects={"at(robot,room2)"} ), Action( "pickup(box,room1)", preconds={"at(robot,room1)","at(box,room1)","handempty(robot )"}, add_effects={"holding(robot,box)"}, del_effects={"at(box,room1)","handempty(robot)"} ), Action( "putDown(box,room2)", preconds={"at(robot,room2)","holding(robot,box)"}, add_effects={"at(box,room2)","hand empty(robot)"}, del_effects={"holding(robot,box)"} ) ] initial_state={ "at(robot,room1)", "at(box,room1)", "handempty(robot)" } goal_state={ "at(box,room2)" } plan=strips_planner(initial_state,goal_state,actions) print("Plan Fou nd:") if plan: for step,action in enumerate(plan,1): print(f"{step}.{action}") else: print("No plan found") output: Plan Found: 1.pickup(box,room1) 2.Move(room1,room2) 3.putDown(box,room2) 11.cooperative planning import heapq GRID_WIDT H=6 GRID_HEIGHT=6 OBSTACLES={(2,2),(3,2)} def astar(start,goal,reserved): """ star,goal:(x,y) reserved:set of (x,y,t) occupied by other robots """ def heuristic(a,b): return abs(a[0] - b[0]+abs(a[1] - b[1])) open_set=[] heap q.heappush(open_set,(0,start,0,[start])) visited=set() while open_set: cost,current,time,path=heapq.heappop(open_set) if(current,time) in visited: continue visited.add((current,time)) if(current==goal): return path for dx,dy in[(0,1),(1,0),(0, - 1),( - 1,0),(0,0)]: nx,ny=current[0]+dx,current[1]+dy nt=time+1 if not (0 <= nx < GRID_WIDTH and 0<=ny < GRID_HEIGHT): continue if(nx, ny) in OBSTACLES: continue if(nx,ny,nt) in reserved: continue new_cost = cost+1+heuristic((nx,ny),goal) heapq.heappush( open_set, (new_cost,(nx,ny),nt,path+ [(nx,ny)]) ) return None def cooperativeplanning(robots): """ robots:dict{robot_id:(start,goal)} """ plans={} reserved=set() for robot_id,(start,goal) in robots.items(): path=astar(start,goal,reserved) if path is None: raise Exception(f"No path found for robot {robot_id}") plans[robot_id]=path for t,pos in enumerate(path): reserved.add((pos[0],pos[1],t)) return plans def simulate(plans): max_time=max(len( p) for p in plans.values()) print(" \ n --- Simulation Start --- ") for t in range(max_time): print(f" \ n Time {t}:") for robots,path in plans.items(): pos=path[t] if t<len(path) else path[ - 1] print(f"Robot {robots } - >{pos}") robots={ "R1":((0,0),(5,5)), "R2":((5,0),(0,5)), "R3":((0,5),(5,0)) } plans=cooperativeplanning(robots) for r,p in plans.items(): print(f"{r} path: {p}") simulate(plans) output: R1 path: [(0, 0), (0, 1), (1, 1), (1, 2), (1, 3) , (2, 3), (3, 3), (3, 4), (4, 4), (4, 5), (5, 5)] R2 path: [(5, 0), (4, 0), (3, 0), (2, 0), (1, 0), (0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5)] R3 path: [(0, 5), (0, 4), (1, 4), (1, 3), (2, 3), (3, 3), (4, 3), (4, 2), (4, 1), (4, 0), (5, 0)] --- Simula tion Start --- Time 0: Robot R1 - >(0, 0) Robot R2 - >(5, 0) Robot R3 - >(0, 5) Time 1: Robot R1 - >(0, 1) Robot R2 - >(4, 0) Robot R3 - >(0, 4) 12.Naive bayes import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklea rn.feature_extraction.text import CountVectorizer,TfidfVectorizer from sklearn.naive_bayes import MultinomialNB,GaussianNB from sklearn.metrics import accuracy_score,classification_report,confusion_matrix data=pd.read_csv("C:/Users/yasha/OneDrive/Desktop/s ms_spam.csv",encoding='lati n - 1') data['label']=data['label'].map({'ham':0,'spam':1}) X=data['message'] y=data['label'] X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.25,random_state =42,stratify=y) vectorizer=CountVectorizer(stop_words='engl ish') X_train_vec=vectorizer.fit_transform(X_train) X_test_vec=vectorizer.transform(X_test) mnb=MultinomialNB() mnb.fit(X_train_vec,y_train) y_pred_mnb=mnb.predict(X_test_vec) print("Multinomial Naive Bayes") print("Accuracy:",accuracy_score(y_test,y_pred_ mnb)) print(confusion_matrix(y_test,y_pred_mnb)) print(classification_report(y_test,y_pred_mnb)) tfidf=TfidfVectorizer(stop_words='english',max_features=3000) X_train_tfidf=tfidf.fit_transform(X_train).toarray() X_test_tfidf=tfidf.transform(X_test).toarray () gnb=GaussianNB() gnb.fit(X_train_tfidf,y_train) y_pred_gnb=gnb.predict(X_test_tfidf)