0% found this document useful (0 votes)
35 views11 pages

AI Practicallll

Uploaded by

yashupadhye2021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views11 pages

AI Practicallll

Uploaded by

yashupadhye2021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

In [2]: ​

def dfs(graph,initial,goal):
stack=[(initial,[initial])]
visited = set()

while stack:
node, path = stack.pop()

if node not in visited:


visited.add(node)

if node == goal:
return path

for neighbor in graph.get(node,[]):


stack.append((neighbor,path+[neighbor]))

return None

graph={ 'A':['B','C'],
'B':['D','E'],
'C':['F','G'],
'D':['H','I'],
'E':[],
'F':['K'],
'G':[],
'H':[],
'I':[],
'K':[]}

print(f"path is : {dfs(graph,'A','G')}")

path is : ['A', 'C', 'G']


In [3]: from collections import deque


def BFS(graph,initial,goal):
queue=deque([(initial,[initial])])
visited = set()

while queue:
node, path = queue.popleft()

if node not in visited:


visited.add(node)

if node == goal:
return path

for neighbor in graph.get(node,[]):


queue.append((neighbor,path+[neighbor]))

return None

graph={ 'A':['B','C'],
'B':['D','E'],
'C':['F','G'],
'D':['H','I'],
'E':[],
'F':['K'],
'G':[],
'H':[],
'I':[],
'K':[]}


initial_node='A'
goal_node='G'

result_path = BFS(graph,initial_node,goal_node)

print(f"path is : {result_path}")

path is : ['A', 'C', 'G']


In [10]: import numpy as np

def f(x):
return -x**2 + 4*x

def hill_climbing(f, x0, step_size=0.1, max_iters=100):
x = x0
for _ in range(max_iters):
f_prime = (f(x + step_size) - f(x - step_size)) / (2 * step_size)

if f_prime > 0:
x += step_size
else:
break
return x

x0 = 1

max_x = hill_climbing(f, x0)

print(f"Maximum found at x = {max_x:.4f}")
print(f"Function value at maximum: {f(max_x):.4f}")

Maximum found at x = 2.0000


Function value at maximum: 4.0000

In [15]: # SLip 3,21 a remove punctuations



import re

def remove_punctuations(text):
pattern = r"[^\w\s]"
no_punct = re.sub(pattern, "", text)
return no_punct

text = "T!!his i!!s a stri!!!ng with some punctuation! h!!!!ello."
text_without_punctuations = remove_punctuations(text)
print(text_without_punctuations)

This is a string with some punctuation hello


In [37]: import nltk
from nltk.corpus import stopwords

def remove_stop_words(text_file):
with open(text_file, "r") as f:
text = f.read()

# Tokenize the text
tokens = nltk.word_tokenize(text)

# Download nltk stop words if not already downloaded
#nltk.download('stopwords')

# Get stop words in English
stop_words = stopwords.words("english")

# Remove stop words from the tokens
filtered_words = [word for word in tokens if word not in stop_words]

return filtered_words

# Example usage
text_file = "password.txt"
filtered_words = remove_stop_words(text_file)

print(f"Filtered text: {' '.join(filtered_words)}")

Filtered text: b equal c also equal .


In [41]: ### 15

def print_board(b):
print(" | |")
print(f" {b[0]} | {b[1]} | {b[2]} ")
print("___|___|___")
print(" | |")
print(f" {b[3]} | {b[4]} | {b[5]} ")
print("___|___|___")
print(" | |")
print(f" {b[6]} | {b[7]} | {b[8]} ")
print(" | |")

def get_move(b, player):
while True:
move = input(f"{player}'s turn. Enter a number from 1-9: ")
if move.isdigit() and int(move) in range(1, 10) and b[int(move)-1]
return int(move) - 1
print("Invalid move. Try again.")

def check_win(b):
for i in range(0, 9, 3):
if b[i] == b[i+1] == b[i+2] != " ":
return b[i]
for i in range(3):
if b[i] == b[i+3] == b[i+6] != " ":
return b[i]
if b[0] == b[4] == b[8] != " ":
return b[0]
if b[2] == b[4] == b[6] != " ":
return b[2]
if " " not in b:
return "Tie"
return None

def play_game():
b = [" "]*9
players = ["X", "O"]
turn = 0
while True:
print_board(b)
move = get_move(b, players[turn])
b[move] = players[turn]
winner = check_win(b)
if winner is not None:
print_board(b)
if winner == "Tie":
print("It's a tie!")
else:
print(f"{winner} wins!")
return
turn = (turn + 1) % 2

play_game()
| |
| |
___|___|___
| |
| |
___|___|___
| |
| |
| |
X's turn. Enter a number from 1-9: 1
| |
X | |
___|___|___
| |
| |
___|___|___
| |
| |
| |
O's turn. Enter a number from 1-9: 2
| |
X | O |
___|___|___
| |
| |
___|___|___
| |
| |
| |
X's turn. Enter a number from 1-9: 3
| |
X | O | X
___|___|___
| |
| |
___|___|___
| |
| |
| |
O's turn. Enter a number from 1-9: 4
| |
X | O | X
___|___|___
| |
O | |
___|___|___
| |
| |
| |
X's turn. Enter a number from 1-9: 5
| |
X | O | X
___|___|___
| |
O | X |
___|___|___
| |
| |
| |
O's turn. Enter a number from 1-9: 6
| |
X | O | X
___|___|___
| |
O | X | O
___|___|___
| |
| |
| |
X's turn. Enter a number from 1-9: 7
| |
X | O | X
___|___|___
| |
O | X | O
___|___|___
| |
X | |
| |
X wins!
File "C:\Users\Mehta\AppData\Local\Temp/ipykernel_22308/1877880436.py",
line 89
break
^
IndentationError: unexpected indent

In [2]: # 7 10 22 b
# pip install nltk
import nltk
from nltk.chat.util import Chat, reflections

chatbot_responses = [ [ r"hello|hi|hey",
["Hello!" , "Hi Buddy" , "Hii" , "Hey" , "Hey man"]
],
[ r"what is your name|what is your name?|your name|ur
["You called me Assistant" , "ChatBot" , "I don't h
],
[ r"Good Morning|Morning",
["You Look Gorgeous :-) Good Morning" , " Very Good
],
[ r"Bye|bai|Good Bye",
["Bye! see you later..." , "'ll be back ?" ,"bye","
]
]
chatbot = Chat(chatbot_responses, reflections)

print("hello! How can I help you?..... \n say 'exit' for end the conversati

while True:
user_input = input("YOU -> ")

if user_input.lower() == "exit":
print(" Bye ")
break
response = chatbot.respond(user_input)
print("BOT :",response)

hello! How can I help you?.....


say 'exit' for end the conversation

YOU -> morning


BOT : You Look Gorgeous :-) Good Morning
YOU -> name
BOT : You called me Assistant
YOU -> hey
BOT : Hii
YOU -> bye
BOT : bye
YOU -> bye
BOT : Bye! see you later...
YOU -> bye
BOT : 'll be back ?
YOU -> bye
BOT : bye
YOU -> bye
BOT B ! l t
In [4]: import nltk
from nltk.chat.util import Chat, reflections

chat_reflections=[
[ r"hello|hey",["hii","whatsapp"]],
[ r"Good Morning|morning",["very Good Morning","have a good
]

chatbot = Chat(chat_reflections,reflections)

print("write exit for termination")

while True:
user_i = input("U ")

if user_i.lower() == "exit":
print("Bye")
break
response = chatbot.respond(user_i)
print("BOT : ",response)

write exit for termination


U hey
BOT : hii
U good morning
BOT : very Good Morning
U bye
BOT : None
U exit
Bye

In [7]: def count_case(text):


upper = 0
lower = 0
for char in text:
if char.isupper():
upper += 1
elif char.islower():
lower += 1
return upper, lower

# Example usage
text = input("Enter a string: ")
upper_case, lower_case = count_case(text)

print(f"Number of upper case letters: {upper_case}")
print(f"Number of lower case letters: {lower_case}")

Enter a string: Hello babe


Number of upper case letters: 1
Number of lower case letters: 8

In [ ]: ​

You might also like