Name:Malek Safin Subject Name: Fundamental of AI Batch No: CO2
EnrolmentNo:22601030749 Subject Code: 4350705
PRACTICAL : 1
Aim: Develop A Program That Read Rules From The Rules File And Acts
Accordingly For Given User Input. For This, Create A Text File Of Five
Rules Of Any Situation And Ask The User To Give Input And According
To The Rules Give The Response.
INPUT:
def load(file_path):
rule={}
with open(file_path,'r') as file:
for line in file:
if ':' in line:
key,value=line.strip().split(':',1)
rule[key.lower()]=value
return rule
def get_response(rules,user_input):
return rules.get(user_input.lower(),"I don't understand that.")
def main():
rules_file="049.txt"
rules=load(rules_file)
print("Chat with jarvis")
while True:
user_input=input("You : ")
if user_input.lower() in ["exit","quit"]:
print("Goodby !")
break
response=get_response(rules,user_input)
print("AI : ",response)
if name == " main ":
main()
print(“This Program is Perform by Malek Safin”)
OUTPUT:
AYD/CO/2024-25/ODD/ Page
Name:Malek Safin Subject Name: Fundamental of Batch No:
EnrolmentNo:226010307 AI Subject Code: 4350705
PRACTICAL : 5
AIM: Read Data From A Csv File Using Panda Library.
INPUT:
import pandas as pd
df=pd.read_csv('034.csv')
print(df.to_string())
print(“Performed by Malek Safin”)
OUTPUT:
INPUT:
print(df.head())
print(“Performed by Malek Safin”)
OUTPUT:
AYD/CO/2024-25/ODD/ Page
Name:Malek Safin Subject Name: Fundamental of Batch No:
EnrolmentNo:226010307 AI Subject Code: 4350705
INPUT:
print(df.head(10))
print(“Performed by Malek Safin”)
OUTPUT:
AYD/CO/2024-25/ODD/ Page
Name:Malek Safin Subject Name: Fundamental of Batch No:
EnrolmentNo:226010307 AI Subject Code: 4350705
PRACTICAL : 4
AIM: Write a python program to generate Calendar for the given month
and year?
INPUT:
import calendar
def generate_calendar(year,month):
cal = calendar.TextCalendar(calendar.SUNDAY)
month_calendar = cal.formatmonth(year,month)
return month_calendar
year = int(input("Enter year:"))
month = int(input("Enter month:"))
print(generate_calendar(year,month))
print("Performed by: Malek Safin ")
OUTPUT:
AYD/CO/2024-25/ODD/ Page
Name:Malek Safin Subject Name: Fundamental of Batch No:
EnrolmentNo:226010307 AI Subject Code: 4350705
PRACTICAL : 5
AIM: Write a python program to implement Breadth First Search
Traversal?
INPUT:
from collections import deque
class treenode:
def init (self,value):
self.value=value
self.children=[]
def bfs_search_path_tree(root,target_value):
if root is None:
return None queue=deque([(root,
[root.value])]) while queue:
node,path=queue.popleft()
if (node.value==target_value):
return path
for child in node.children: queue.append((child,path+
[child.value]))
return None
if name ==" main__":
root=treenode('A')
root.children=[treenode('B'),treenode('C')]
root.children[0].children=[treenode('D'),treenode('E')]
root.children[1].children=[treenode('F')]
target_elmnt="F"
path=bfs_search_path_tree(root,target_elmnt)
if path:
print(f" path from root to {target_elmnt} : ",'->'.join(path))
print("This programm is performed by Malek Safin")
else:
print(f" Node {target_elmnt} not fond in the tree.")
OUTPUT:
AYD/CO/2024-25/ODD/ Page
Name:Malek Safin Subject Name: Fundamental of Batch No:
EnrolmentNo:226010307 AI Subject Code: 4350705
PRACTICAL : 8
AIM : Write a program to implement Tic-Tac-Toe game using python
INPUT:
def print_board(board):
"""prints yhe tic-tac board."""
print("\n")
for i in range(3):
print(" | ".join(board[i*3:(i+1)*3]))
if i < 2:
print("--------")
print("\n")
def check_winner(board, player):
"""checks if the player has won the game."""
win_conditions = [
[0,1,2], [3,4,5], [6,7,8], # Rows
[0,3,6], [1,4,7], [2,5,8], # Colums
[0,4,8], [2,4,6] # Diagonals
]
for condition in win_conditions:
if all(board[i] == player for i in condition):
return True
return False
def tic_tac_toe():
"""main function to play the tic-tac-toe game."""
board = [" "for _ in range(9)]
players = ["x", "0"]
turn = 0
AYD/CO/2024-25/ODD/ Page 6
Name:Malek Safin Subject Name: Fundamental of Batch No:
EnrolmentNo:226010307 AI Subject Code: 4350705
print("welcome to tic-tac-toe!")
print_board(board)
while True:
player = players[turn % 2]
print(f"player {player}' s turn.")
move = input("enter a position (1-9): ")
if not move.isdigit() or not 1 <= int(move) <=9:
print("invalid input. enter a number between 1 and 9.")
continue
move = int(move) -1
if board[move] != " ":
print("position already taken. try again.")
continue
board[move] = player
print_board(board)
if check_winner(board, player):
print(f"player {player} wins!")
break
if " " not in board:
print("it's a draw!")
break
turn += 1
if name ==" main ":
AYD/CO/2024-25/ODD/ Page 7
Name:Malek Safin Subject Name: Fundamental of Batch No:
EnrolmentNo:226010307 AI Subject Code: 4350705
tic_tac_toe()
print("This programm is performed by malek safin")
OUTPUT:
AYD/CO/2024-25/ODD/ Page 8
Name:Malek Safin Subject Name: Fundamental of Batch No:
EnrolmentNo:226010307 AI Subject Code: 4350705
AYD/CO/2024-25/ODD/ Page 9
Name:Malek Safin Subject Name: Fundamental of Batch No:
EnrolmentNo:226010307 AI Subject Code: 4350705
PRACTICAL : 9
AIM: Perform math functions using NumPy library.
INPUT:
import numpy as np
#creating a 1D array
arr = np.array([1,2,3,4,5])
#Basic Operations
add_scalar = arr + 5
sub_scalar = arr - 5
mul_scalar = arr * 2
div_scalar = arr / 2
#Mathematical operations
sqrt_arr = np.sqrt(arr)
exp_arr = np.exp(arr)
sin_arr = np.sin(arr)
log_arr = np.log(arr)
power_arr = np.power(arr,3)
log_arr = np.log(arr)
log2_arr = np.log2(arr)
log10_arr = np.log10(arr)
min_arr = np.min(arr)
max_arr = np.max(arr)
sorted_arr = np.sort(arr)
sum_arr = np.sum(arr)
mean_arr = np.mean(arr)
median_arr = np.median(arr)
std_arr = np.std(arr)
var_arr = np.var(arr)
#Print result
print(add_scalar)
AYD/CO/2024-25/ODD/ Page
Name:Malek Safin Subject Name: Fundamental of Batch No:
EnrolmentNo:226010307 AI Subject Code: 4350705
print(sub_scalar)
print(mul_scalar)
print(div_scalar)
print(sqrt_arr)
print(exp_arr)
print(sin_arr)
print(log_arr)
print(power_arr)
print(log_arr)
print(log2_arr)
print(log10_arr)
print(min_arr)
print(max_arr)
print(sorted_arr)
print(sum_arr)
print(mean_arr) #Mean
print(median_arr) #Median
print(std_arr) #standard deviation
print(var_arr) #variance
print("Performed by malek safin")
OUTPUT:
AYD/CO/2024-25/ODD/ Page
Name:Malek Safin Subject Name: Fundamental of Batch No:
EnrolmentNo:226010307 AI Subject Code: 4350705
PRACTICAL : 10
AIM: Identify the missing values from given CSV file.
INPUT:
import pandas as pd
#Load the csv file
file_path = "034.csv"
df = pd.read_csv(file_path)
print("original Data Frame")
print(df)
#identify missing values
missing_values = df.isnull()
#Display missing values
print("\nMissing values(True indicates missing values)")
print(missing_values)
#count the number of missing values in each column
missing_count = df.isnull().sum()
print("\nNumber of missing values in Each column:")
print(missing_count)
print("Performed by malek safin")
AYD/CO/2024-25/ODD/ Page
Name:Malek Safin Subject Name: Fundamental of Batch No:
EnrolmentNo:226010307 AI Subject Code: 4350705
OUTPUT:
AYD/CO/2024-25/ODD/ Page
Name:Malek Safin Subject Name: Fundamental of Batch No:
EnrolmentNo:226010307 AI Subject Code: 4350705
PRACTICAL : 11
AIM: write a program to identify the noisy value of the age data set.
INPUT:
import numpy as np
import pandas as pd
file_path = 'data.csv'
df = pd.read_csv(file_path)
print("original Dataframe: ")
print(df)
min_age = 0
max_age = 120
noisy_values = df[(df['Age']<min_age) | (df['Age']>max_age)]
print("\nNoisy Values (Age Outside the Range 0-120): ")
print(noisy_values)
#Identify Outliers using the Interquartile Range (IQR) Method
Q1 = df['Age'].quantile(0.25)
Q3 = df['Age'].quantile(0.75)
IQR =Q3 - Q1
#Define the Bounds for non-outliers
lower_bound = Q1 - 1.5*IQR
upper_bound = Q3 + 1.5*IQR
#Identify Outliers
outliers = df[(df['Age'] < lower_bound) | (df['Age'] > upper_bound)]
print("\nOutliers Identified using IQR Method: ")
print(outliers)
print("\n Performed by Safin malek")
AYD/CO/2024-25/ODD/ Page
Name:Malek Safin Subject Name: Fundamental of Batch No:
EnrolmentNo:226010307 AI Subject Code: 4350705
OUTPUT:
AYD/CO/2024-25/ODD/ Page
Name:Malek Safin Subject Name: Fundamental of Batch No:
EnrolmentNo:226010307 AI Subject Code: 4350705
PRACTICAL : 12
AIM: write a python program to implement simple chatbot.
INPUT:
import nltk
from nltk.chat.util import Chat, reflections
nltk.download('punkt')
#list of patterns and Responses
pairs = [
(r'hi|hello|hey',['Hello','Hi there!','Hey!']),
(r'how are you?',['I am just a bot, but I am doing fine!How about you?']),
(r'what is your name?',['I am a simple chatbot created using nltk.','you can call me chatbot']),
(r'bye',['Goodbye!','see you later!','Bye!']),
(r'(.*)',['Sorry, I do not understand. Can you please rephrase?'])
]
chatbot = Chat(pairs, reflections)
def start_chatbot():
print("chatbot: Hi! How can I assist you? (type'bye' to exit)")
while True:
user_input = input("You: ").lower()
if user_input == "bye":
print("Chatbot: Goodbye! Have a Great Day!")
break
else:
print("Chatbot: ", chatbot.respond(user_input))
start_chatbot()
print("\nPerformed by Safin Malek ")
AYD/CO/2024-25/ODD/ Page
Name:Malek Safin Subject Name: Fundamental of Batch No:
EnrolmentNo:226010307 AI Subject Code: 4350705
OUTPUT:
AYD/CO/2024-25/ODD/ Page
Name:Malek Safin Subject Name: Fundamental of Batch No:
EnrolmentNo:226010307 AI Subject Code: 4350705
PRACTICAL : 18
AIM: Write a python program to remove stop words for a given passage
from a text file using NLTK?
INPUT:
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
nltk.download('punkt')
def remove_stop_words(file_path):
with open(file_path,'r')as file:
text = file.read()
words = word_tokenize(text)
stop_words = set(stopwords.words('english'))
filtered_words = [word for word in words if words if word.lower() not in stop_words]
filtered_text = ' '.join(filtered_words)
return filtered_text
if name == " main ":
file_path ='034.txt'
cleaned_text = remove_stop_words(file_path)
print("Original Text: ")
print(open(file_path).read())
print("\nCleaned Text: ")
print(cleaned_text)
print(“performed by Safin malek”)
OUTPUT:
AYD/CO/2024-25/ODD/ Page
Name:Malek Safin Subject Name: Fundamental of Batch No:
EnrolmentNo:226010307 AI Subject Code: 4350705
PRACTICAL : 14
AIM: Write a python program to for Text Classification for the give
sentence using NLTK?
INPUT:
import nltk
from nltk.corpus import movie_reviews
from nltk.classify import NaiveBayesClassifier
from nltk.classify.util import accuracy
from nltk import word_tokenize
# Download necessary NLTK datasets (only needed the first time)
nltk.download('movie_reviews')
nltk.download('punkt')
# Function to extract features from a document (sentence)
def extract_features(words):
return {word: True for word in words}
# Load movie reviews dataset from NLTK
# The dataset contains labeled sentences as either positive or negative
positive_ids = movie_reviews.fileids('pos')
negative_ids = movie_reviews.fileids('neg')
# Create the dataset of tuples with (words, label)
positive_features =[(extract_features(movie_reviews.words(fileids=[file])), 'Positive')for file
in positive_ids]
negative_features =[(extract_features(movie_reviews.words(fileids=[file])), 'Negative')for
file in negative_ids]
# Split data into training and testing sets (80% train, 20% test)
train_data = positive_features[:800] + negative_features[:800]
test_data = positive_features[800:] + negative_features[800:]
# Train the Naive Bayes Classifier
classifier = NaiveBayesClassifier.train(train_data)
# Evaluate the classifier
print(f"Accuracy: {accuracy(classifier, test_data):.2f}")
# Function to classify a new sentence
def classify_sentence(sentence):
words = word_tokenize(sentence.lower())
features = extract_features(words)
return classifier.classify(features)
# Test classification on a new sentence
new_sentence = "Best movie"
result = classify_sentence(new_sentence)
print(f"The sentence: '{new_sentence}' is classified as: {result}")
# You can also check the most informative features
classifier.show_most_informative_features(10)
print(“performed by Safin malek”)
AYD/CO/2024-25/ODD/ Page
Name:Malek Safin Subject Name: Fundamental of Batch No:
EnrolmentNo:226010307 AI Subject Code: 4350705
OUTPUT:
AYD/CO/2024-25/ODD/ Page