0% found this document useful (0 votes)
34 views12 pages

AI Practical Assignments

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)
34 views12 pages

AI Practical Assignments

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/ 12

Artificial Intelligence Solved Practical Assignments

1. (a) Python Program to Print Multiplication Table of a Number.

num = int(input("Enter the number: "))

print("Multiplication Table of", num)


for i in range(1, 11):
print(num,"X",i,"=",num * i)

(b). Python program to check if given number is prime or not

number = int(input("Enter any number: "))

if number > 1:

for i in range(2, number):

if (number % i) == 0:

print(number, "is not a prime number")

break

else:

print(number, "is a prime number")

else:

print(number, "is not a prime number")

(c)Python Program to find factorial of the given no.

num = int(input("Enter a number: "))

factorial = 1

if num < 0:

print("Sorry, factorial does not exist for negative numbers")

elif num == 0:

print("The factorial of 0 is 1")

else:
for i in range(1,num + 1):

factorial = factorial*i

print("The factorial of",num,"is",factorial)

(c)Python Program to check whether no Armstrong is or not.

num = int(input("Enter a number: "))


sum = 0
temp = num

while temp > 0:


digit = temp % 10
sum += digit ** 3
temp //= 10

if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

(d)Python Program to display the Fibonacci sequence up to nth term

nterms = int(input("How many terms? "))

# first two terms


n1, n2 = 0, 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

2. (a)Write a python program to implement list operations (Nested List, Length,


Concatenation,Membership,Iteration,Indexing and Slicing)?
my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])
print("Length",my_list,":",len(my_list))
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
# Error! Only integer can be used for indexing
#my_list[4.2]
# Nested List
n_list = [[1,3,5,7], [2,4,6,8,10]]
# Nested indexing
# Output: 3
print(n_list[0][1])
# Output: 8
print(n_list[1][3])
# Nested List2
n_list2 = ["Happy", [2,0,1,5]]
# Nested indexing
# Output: a
print(n_list2[0][1])
# Output: 5
print(n_list2[1][3])
concat1=[1,3,5]
concat2=[7,8,9]
print("Concatenation:",concat1,concat2,":",concat1+concat2)
repetion_string="Hello"
print("Repetition:",repetion_string,repetion_string * 4)

(b) Write a python program to implement list operations (add, append, extend & delete)
myList = ["Earth", "revolves", "around", "Sun"]
print(myList)
print(len(myList))
print(myList[0])
print(myList[3])
#Slice elements from a list
print(myList[1:3])
#Use negative index
print(myList[-1])
#print(myList[4])
#add element to a list
myList.insert(0,"The")
print(myList)
print(len(myList))
myList.insert(4,"the")
print(myList)
#append an element to a list
myList.append("continuously")
print(myList)
print(len(myList))
#When use extend the argument should be another list
#the elements of that list will be added
#to the current list as individual elements
myList.extend(["for", "sure"])
print(myList)
print(len(myList))
#you can append a sublist to the current list using append
myList.append(["The","earth","rotates"])
print(myList)
print(len(myList))
#delete a element in the list using element
myList.remove("The")
#delete a element in the list using index
myList.remove(myList[3])
print(myList)

3. (a)Write a python program to illustrate different set operations like in mathematics.

# define three sets


E = {0, 2, 4, 6, 8};
N = {1, 2, 3, 4, 5};
# set union
print("Union of E and N is",E | N)
# set intersection
print("Intersection of E and N is",E & N)
# set difference
print("Difference of E and N is",E - N)
# set symmetric difference
print("Symmetric difference of E and N is",E ^ N)

(b) Write a python program to generate Calendar for the given month and year?

#to display calendar of given month of the year

import calendar

yy = 2019
mm = 6
print(calendar.month(yy, mm))

# To ask month and year from the user

import calendar
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))

# display the calendar

print(calendar.month(yy, mm))

(c)Write a python program to make a simple calculator that can add, subtract, multiply and
divide using functions

# define functions
def add(x, y):
"This function adds two numbers"
return x + y

def subtract(x, y):


"This function subtracts two numbers"
return x - y

def multiply(x, y):


"This function multiplies two numbers"
return x * y

def divide(x, y):


"This function divides two numbers"
return x / y

# take input from the user

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

choice = input("Enter choice(1/2/3/4):")

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))

if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))

elif choice == '2':


print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':


print(num1,"*",num2,"=", multiply(num1,num2))

elif choice == '4':


print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")

4. Write a python program to implement simple Chatbot?

print("Simple Question and Answering Program")


print("=====================================")
print(" You may ask any one of these questions")
print("Hi")
print("How are you?")
print("Are you working?")
print("What is your name?")
print("what did you do yesterday?")
print("Quit")
while True:

question = input("Enter one question from above list:")


question = question.lower()
if question in ['hi']:
print("Hello")
elif question in ['how are you?','how do you do?']:
print("I am fine")
elif question in ['are you working?','are you doing any job?']:
print("yes. I'am working in KLU")
elif question in ['what is your name?']:
print("My name is Emilia")
name=input("Enter your name?")
print("Nice name and Nice meeting you",name)
elif question in ['what did you do yesterday?']:
print("I saw Bahubali 5 times")
elif question in ['quit']:
break
else:
print("I don't understand what you said")

5. Write a python program to implement Bredth First Search Algorithm.

graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}

visited = [] # List to keep track of visited nodes.


queue = [] #Initialize a queue

def bfs(visited, graph, node):


visited.append(node)
queue.append(node)

while queue:
s = queue.pop(0)
print (s, end = " ")

for neighbour in graph[s]:


if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)

# Driver Code
bfs(visited, graph, 'A') #execution starts here bfs(visited[],Graph,’A’) PC jump to line 12

Explanation

● Lines 3-10: The illustrated graph is represented using an adjacency list. An easy way to do
this in Python is to use a dictionary data structure, where each vertex has a stored list of its
adjacent nodes.

● Line 12: visited is a list that is used to keep track of visited nodes.

● Line 13: queue is a list that is used to keep track of nodes currently in the queue.

● Line 29: The arguments of the bfs function are the visited list, the graph in the form of a
dictionary, and the starting node A.

● Lines 15-26: bfs follows the algorithm described above:

1. It checks and appends the starting node to the visited list and the queue.
2. Then, while the queue contains elements, it keeps taking out nodes from the queue,
appends the neighbors of that node to the queue if they are unvisited, and marks
them as visited.
3. This continues until the queue is empty.

6. Write a python program to implement Depth First Search Algorithm.

graph1 = {
'A' : ['B','S'],
'B' : ['A'],
'C' : ['D','E','F','S'],
'D' : ['C'],
'E' : ['C','H'],
'F' : ['C','G'],
'G' : ['F','S'],
'H' : ['E','G'],
'S' : ['A','C','G']
}

def dfs(graph, node, visited):


if node not in visited:
visited.append(node)
for k in graph[node]:
dfs(graph,k, visited)
return visited

visited = dfs(graph1,'A', [])


print(visited)

Explaination :

A is the root node. So since A is visited, we push this onto the stack.

Stack : A
Let’s go to the branch A-B. B is not visited, so we go to B and push B onto the stack.

Stack : A B
Now, we have come to the end of our A-B branch and we move to the n-1th node which is
A. We will now look at the adjacent node of A which is S. Visit S and push it onto the stack.
Now you have to traverse the S-C-D branch, up to the depth ie upto D and mark S, C, D as
visited.

Stack: A B S C D
Since D has no other adjacent nodes, move back to C and traverse its adjacent branch
E-H-G to the depth and push them onto the stack.

Stack : A B S C D E H G
On reaching D, there is only one adjacent node ie F which is not visited. Push F onto the
stack as well.

Stack : A B S C D E H G F
This stack itself is the traversal of the DFS.

7. Write a Program to implement water jug problem.

print("Water Jug Problem")


x=int(input("Enter X:"))
y=int(input("Enter Y:"))
while True:

rno=int(input("Enter the Rule No"))


if rno==1:
if x<4:
x=4

if rno==2:
if y<3:
y=3

if rno==5:
if x>0:
x=0

if rno==6:
if y>0:
y=0

if rno==7:
if x+y>= 4 and y>0:
x,y=4,y-(4-x)

if rno==8:
if x+y>=3 and x>0:
x,y=x-(3-y),3

if rno==9:
if x+y<=4 and y>0:
x,y=x+y,0

if rno==10:
if x+y<=3 and x>0:
x,y=0,x+y

print("X =" ,x)


print("Y =" ,y)
if (x==2):
print(" The result is a Goal state")
break

8. Write a Program to implement K-Nearest Neighbor algorithm

import numpy as np

import pandas as pd

from matplotlib import pyplot as plt

from sklearn.datasets import load_breast_cancer

from sklearn.metrics import confusion_matrix


from sklearn.neighbors import KNeighborsClassifier

from sklearn.model_selection import train_test_split

import seaborn as sns

sns.set()

breast_cancer = load_breast_cancer()

X = pd.DataFrame(breast_cancer.data, columns=breast_cancer.feature_names)

X = X[['mean area', 'mean compactness']]

y = pd.Categorical.from_codes(breast_cancer.target, breast_cancer.target_names)

y = pd.get_dummies(y, drop_first=True)

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)

knn = KNeighborsClassifier(n_neighbors=5, metric='euclidean')

knn.fit(X_train, y_train)

y_pred = knn.predict(X_test)

sns.scatterplot( x='mean area', y='mean compactness', hue='benign', data=X_test.join(y_test,


how='outer'))

plt.scatter( X_test['mean area'], X_test['mean compactness'], c=y_pred,cmap='coolwarm',alpha=0.7)

confusion_matrix(y_test, y_pred)

9. Write a program to implement Simple Regression algorithm


(Download salary_data.csv dataset).

#Importing libraries

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset


dataset = pd.read_csv('salary_data.csv')
X = dataset.iloc[:, :-1].values #get a copy of dataset exclude last column
y = dataset.iloc[:, 1].values #get array of dataset in column 1st

# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/3, random_state=0)
# Fitting Simple Linear Regression to the Training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)

# Visualizing the Training set results


viz_train = plt
viz_train.scatter(X_train, y_train, color='red')
viz_train.plot(X_train, regressor.predict(X_train), color='blue')
viz_train.title('Salary VS Experience (Training set)')
viz_train.xlabel('Year of Experience')
viz_train.ylabel('Salary')
viz_train.show()

# Visualizing the Test set results


viz_test = plt
viz_test.scatter(X_test, y_test, color='red')
viz_test.plot(X_train, regressor.predict(X_train), color='blue')
viz_test.title('Salary VS Experience (Test set)')
viz_test.xlabel('Year of Experience')
viz_test.ylabel('Salary')
viz_test.show()

# Predicting the result of 5 Years Experience


y_pred =regressor.predict(np.array([5]).reshape(1, 1))

10. Write a program to implement Random Forest Algorithm


Dataset: Bengaluru Housing Dataset

#Step 1: Load required packages


import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.impute import SimpleImputer

#Step 2: Load the Begaluru house price dataset


data = pd.read_csv("Bengaluru_House_Data.csv")

#Step 3: Perform data preprocessing to manage missing values in dataset


x = pd.DataFrame(data.iloc[:,:-1])
y = pd.DataFrame(data.iloc[:,-1])
imp = SimpleImputer(missing_values=np.nan, strategy='mean')
imp.fit(x)
x = imp.transform(x)

#Step 4: Split the dataset into train and test sets


x_trn, x_tst, y_trn, y_tst = train_test_split(x, y, test_size = 0.20)

#Step 5: Build the model with theRandom Forest tree regressor function
regressor = RandomForestRegressor(n_estimators=100, random_state=0)
regressor.fit(x_trn,y_trn.values.ravel())

#Step 6: Visualize the tree using Graphviz


estimator = regressor.estimators_[10]
cols = ['Room', 'Land_size', 'Balcony']
from sklearn.tree import export_graphviz
# Export as dot file
export_graphviz(estimator, out_file='tree.dot',
feature_names = cols,
class_names = 'price',
rounded = True, proportion = False,
precision = 2, filled = True)

#Step 7: Predict the values


y_pred = regressor.predict(x_tst)
x_new = [[4],[1150],[2]]
y1_pred = regressor.predict(np.array(x_new).reshape(1, 3))
print(y1_pred)

You might also like