You are on page 1of 30

18AIL57- Artificial Intelligence Laboratory 2022-23

Installation Procedure
The installation procedure of Python IDLE editor in windows is given below:
1. Visit https://www.python.org/ and download the latest version of python executable file.
2. Double click on python-3.7.2.exe file
3. Click on Run button
4. Add Python 3.7 to Path. Then click Install now
5. Do you want to allow the following program to make changes to this computer ?
Click YES

re
6. Set up Progress ……….
7. The Setup was successful. Click Close

ge
8. Then go to C:\Users\Online-67 select Organize → Folder and Search options → Select
Show all folders → In View select Show Hidden files and folders and drives → Click OK
9. Then go to C:\Users\Online-67\AppData\Local\Programs\Python\Python37-32
9.1. Copy the above Path

an
9.2. Go to search on your computer and type env
9.3. Click Edit the system environment variables
9.4. Click Environment Variables
9.5. Click New in user variables for online-67
av
9.5.1. Variable name : Python
9.5.2. Variable value : Paste the above copied path
9.5.3. Click OK
D

9.6. Click New in system variables


9.6.1. Variable name : Python
9.6.2. Variable value : Paste the above copied path
9.6.3. Click OK( 3 times )
,
IT

10. Then again go to


C:\Users\Online-67\AppData\Local\Programs\Python\Python37-32\Scripts
10.1. Copy the above path
M

10.2. Then follow the same procedure which is in step-9. Give variable name :
Python-Scripts
11. Then go to command prompt and give commands as followed:
G

C:\Users\Online-67 > cd AppData


C:\Users\Online-67\AppData > cd Local
C:\Users\Online-67\AppData\ Local > cd Programs
C:\Users\Online-67\AppData\ Local\Programs > cd Python
C:\Users\Online-67\AppData\ Local\Programs > cd Python37-32
C:\Users\Online-67\AppData\ Local\Programs\Python37-32

Dept. Of. AIML


GMIT, Davangere 1
18AIL57- Artificial Intelligence Laboratory 2022-23

12. Then type Python and hit enter button


13. Then type python-v to check the installation process. If python is installed properly then
it will display the installed version
Python 3.7.2
or else it displays python is an unrecognized internal command.
14. Then test by giving print(‘hello world) in interactive shell
15. From the Start button select IDLE(python).
16. Select New file → Save As → Type program → Check Module → Run Module →

re
Check the output.

ge
an
av
, D
IT
M
G

Dept. Of. AIML


GMIT, Davangere 2
18AIL57- Artificial Intelligence Laboratory 2022-23

PART A
1(a) Write a python program to print the multiplication table for the given number

# Multiplication table (from 1 to 10) in Python

num = int(input("Display multiplication table of? "))

# Iterate 10 times from i = 1 to 10

re
for i in range(1, 11):
print(num, 'x', i, '=', num*i)

ge
output:

Display multiplication table of? 5

an
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
av
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
D

5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
,
IT

1(b) Write a python program to check whether the given number is prime or not?

# Program to check if a number is prime or not


M

# To take input from the user


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

# define a flag variable


flag = False

# prime numbers are greater than 1


if num > 1:

Dept. Of. AIML


GMIT, Davangere 3
18AIL57- Artificial Intelligence Laboratory 2022-23

# check for factors


for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break

# check if flag is True

re
if flag:
print(num, "is not a prime number")
else:

ge
print(num, "is a prime number")

Output:

Enter a number: 21
21 is not a prime number
an
av
1(c) Write a python program to find factorial of the given number.

# Python program to find the factorial of a number provided by the user.


D

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


factorial = 1

# check if the number is negative, positive or zero


,
IT

if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
M

print("The factorial of 0 is 1")


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

factorial = factorial*i
print("The factorial of",num,"is",factorial)

Output:
Enter a number: 4
The factorial of 4 is 24

Dept. Of. AIML


GMIT, Davangere 4
18AIL57- Artificial Intelligence Laboratory 2022-23

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


Length,Concatenation, Membership, Iteration, Indexing and Slicing)

list1=[10,20,30]
list2=['a','b','c']
list3=["AcIT", "CSE", "AIML"]
list4=[23,45,list1,56]
print("list1=", list1)

re
print("list2=", list2)
print("list3=", list3)
print("list4=", list4)

ge
print("list operations")
print("1. Nested list:", list4)
print("2. length of list1:", len(list1))

an
print("3. list concatinate:", list1+list2+list3)
print("4. Membership operator(in, not in):", 23 in list1)
print("5. Repetition operator(*):", list1*3)
print("6. Indexing:", list2[2])
av
print("7. list slicing:", list2[1:2])
print("7. list slicing:", list2[0:2])
print("list comparision operator:", list1<[12,23,24])
D

output:
list1= [10, 20, 30]
list2= ['a', 'b', 'c']
,
IT

list3= ['AcIT', 'CSE', 'AIML']


list4= [23, 45, [10, 20, 30], 56]
list operations
M

1. Nested list: [23, 45, [10, 20, 30], 56]


2. length of list1: 3
3. list concatinate: [10, 20, 30, 'a', 'b', 'c', 'AcIT', 'CSE', 'AIML']
G

4. Membership operator(in, not in): False


5. Repetition operator(*): [10, 20, 30, 10, 20, 30, 10, 20, 30]
6. Indexing: c
7. list slicing: ['b']
7. list slicing: ['a', 'b']
list comparision operator: True

Dept. Of. AIML


GMIT, Davangere 5
18AIL57- Artificial Intelligence Laboratory 2022-23

2(b) Write a python program to implement List methods (Add, Append, Extend &
Delete).

n=int(input("enter the length"))


list1=[]
list2=["AcIT", "Bengaluru", "VTU"]

for i in range(0,n):

re
print("enter the elements")
num=int(input( ))
list1.append(num)

ge
print("list1=", list1)
print("list2=", list2)

an
print("1. add", list1+list2)
print("1. sum of list elements", sum(list1))
list2.append("AIML")
print("2. Append", list2)
av
list1.extend(list2)
print("3.Extend", list1)
list1.remove("VTU")
D

print("4. Delete", list1)

output:
,
IT

enter the length 2


enter the elements 4
enter the elements 1
M

list1= [4, 1]
list2= ['AcIT', 'Bengaluru', 'VTU']
1. add [4, 1, 'AcIT', 'Bengaluru', 'VTU']
G

1. sum of list elements 5


2. Append ['AcIT', 'Bengaluru', 'VTU', 'AIML']
3. Extend [4, 1, 'AcIT', 'Bengaluru', 'VTU', 'AIML']
4. Delete [4, 1, 'AcIT', 'Bengaluru', 'AIML']

Dept. Of. AIML


GMIT, Davangere 6
18AIL57- Artificial Intelligence Laboratory 2022-23

3) Write a python program to implement simple Chatbot with minimum 10


conversations

Main.py

import re
import long_responses as long

re
def message_probability(user_message, recognised_words, single_response=False,
required_words=[]):
message_certainty = 0

ge
has_required_words = True

# Counts how many words are present in each predefined message

an
for word in user_message:
if word in recognised_words:
message_certainty += 1
av
# Calculates the percent of recognised words in a user message
percentage = float(message_certainty) / float(len(recognised_words))
D

# Checks that the required words are in the string


for word in required_words:
if word not in user_message:
has_required_words = False
,
IT

break

# Must either have the required words, or be a single response


M

if has_required_words or single_response:
return int(percentage * 100)
else:
G

return 0

def check_all_messages(message):
highest_prob_list = {}

Dept. Of. AIML


GMIT, Davangere 7
18AIL57- Artificial Intelligence Laboratory 2022-23

# Simplifies response creation / adds it to the dict


def response(bot_response, list_of_words, single_response=False,
required_words=[]):
nonlocal highest_prob_list
highest_prob_list[bot_response] = message_probability(message, list_of_words,
single_response, required_words)

# Responses
-------------------------------------------------------------------------------------------------------

re
response('Hello!', ['hello', 'hi', 'hey', 'sup', 'heyo'], single_response=True)
response('See you!', ['bye', 'goodbye'], single_response=True)
response('I\'m doing fine, and you?', ['how', 'are', 'you', 'doing'],

ge
required_words=['how'])
response('You\'re welcome!', ['thank', 'thanks'], single_response=True)
response('Thank you!', ['i', 'love', 'code', 'palace'], required_words=['code', 'palace'])

# Longer responses
an
response(long.R_ADVICE, ['give', 'advice'], required_words=['advice'])
response(long.R_EATING, ['what', 'you', 'eat'], required_words=['you', 'eat'])
av
best_match = max(highest_prob_list, key=highest_prob_list.get)
# print(highest_prob_list)
D

# print(f'Best match = {best_match} | Score: {highest_prob_list[best_match]}')

return long.unknown() if highest_prob_list[best_match] < 1 else best_match


,
IT

# Used to get the response


def get_response(user_input):
split_message = re.split(r'\s+|[,;?!.-]\s*', user_input.lower())
M

response = check_all_messages(split_message)
return response
G

# Testing the response system


while True:
print('Bot: ' + get_response(input('You: ')))

Dept. Of. AIML


GMIT, Davangere 8
18AIL57- Artificial Intelligence Laboratory 2022-23

long_responses.py
import random

R_EATING = "I don't like eating anything because I'm a bot obviously!"
R_ADVICE = "If I were you, I would go to the internet and type exactly what you wrote
there!"

def unknown():

re
response = ["Could you please re-phrase that? ",
"...",
"Sounds about right.",

ge
"What does that mean?"][
random.randrange(4)]
return response

an
av
, D
IT
M
G

Dept. Of. AIML


GMIT, Davangere 9
18AIL57- Artificial Intelligence Laboratory 2022-23

4) Write a python program to Illustrate Different Set Operations

A = {0, 2, 4, 6, 8};
B = {1, 2, 3, 4, 5};

# union
print("Union :", A | B)

re
# intersection
print("Intersection :", A & B)

ge
# difference
print("Difference :", A - B)

an
# symmetric difference
print("Symmetric difference :", A ^ B)

Output:
av
Union : {0, 1, 2, 3, 4, 5, 6, 8}
Intersection : {2, 4}
Difference : {0, 8, 6}
D

Symmetric difference : {0, 1, 3, 5, 6, 8}

5(a)Write a python program to implement a function that counts the number of


times a string(s1) occurs in another string(s2):
,
IT

my_string = input("Enter a String : ")


my_substring = input("Enter a Substring : ")
M

my_count = my_string.count(my_substring)
G

print("Substring occurs %d times " % my_count)

output:
Enter a String : abacdabhfabcdf
Enter a Substring : ab
Substring occurs 3 times

Dept. Of. AIML


GMIT, Davangere 10
18AIL57- Artificial Intelligence Laboratory 2022-23

5(b)Write a program to illustrate Dictionary operations([],in,traversal)and


methods: keys(),values(),items()

dict={'Name':'Harry','Rollno':30,'Dept':'cse','Marks':97}
print(dict.keys())
print(dict.items())
print(dict.values())
dict.pop('Marks')

re
print(dict)
dict_new=dict.copy()
print(dict_new)

ge
dict.clear()
print(dict)
print('\nName: ', dict.get('Name'))

an
print('\nAge: ', dict.get('Age'))
dict.update({'Age':22})
print(dict)
av
output:
dict_keys(['Name', 'Rollno', 'Dept', 'Marks'])
dict_items([('Name', 'Harry'), ('Rollno', 30), ('Dept', 'cse'), ('Marks', 97)])
D

dict_values(['Harry', 30, 'cse', 97])


{'Name': 'Harry', 'Rollno': 30, 'Dept': 'cse'}
{'Name': 'Harry', 'Rollno': 30, 'Dept': 'cse'}
{}
,
IT

Name: None
M

Age: None
{'Age': 22}
G

Dept. Of. AIML


GMIT, Davangere 11
18AIL57- Artificial Intelligence Laboratory 2022-23

PART - B

re
ge
an
av
, D

1. Implement and Demonstrate Depth First Search Algorithm on Water Jug


IT

Problem

capacity = (12,8,5)
M

x = capacity[0]
y = capacity[1]
G

z = capacity[2]

memory = {}
ans = []

def get_all_states(state):

Dept. Of. AIML


GMIT, Davangere 12
18AIL57- Artificial Intelligence Laboratory 2022-23

a = state[0]
b = state[1]
c = state[2]

if(a==6 and b==6):


ans.append(state)
return True
if((a,b,c) in memory):
return False

re
memory[(a,b,c)] = 1

ge
if(a>0):
if(a+b<=y):
if( get_all_states((0,a+b,c)) ):

an
ans.append(state)
return True
else:
if( get_all_states((a-(y-b), y, c)) ):
av
ans.append(state)
return True
if(a+c<=z):
D

if( get_all_states((0,b,a+c)) ):
ans.append(state)
return True
else:
,
IT

if( get_all_states((a-(z-c), b, z)) ):


ans.append(state)
return True
M

if(b>0):
#empty b into a
G

if(a+b<=x):
if( get_all_states((a+b, 0, c)) ):
ans.append(state)
return True
else:
if( get_all_states((x, b-(x-a), c)) ):

Dept. Of. AIML


GMIT, Davangere 13
18AIL57- Artificial Intelligence Laboratory 2022-23

ans.append(state)
return True
if(b+c<=z):
if( get_all_states((a, 0, b+c)) ):
ans.append(state)
return True
else:
if( get_all_states((a, b-(z-c), z)) ):
ans.append(state)

re
return True
if(c>0):
if(a+c<=x):

ge
if( get_all_states((a+c, b, 0)) ):
ans.append(state)
return True

an
else:
if( get_all_states((x, b, c-(x-a))) ):
ans.append(state)
return True
av
if(b+c<=y):
if( get_all_states((a, b+c, 0)) ):
ans.append(state)
D

return True
else:
if( get_all_states((a, y, c-(y-b))) ):
ans.append(state)
,
IT

return True
return False
initial_state = (12,0,0)
M

print("Starting work...\n")
get_all_states(initial_state)
ans.reverse()
G

for i in ans:
print(i)

Dept. Of. AIML


GMIT, Davangere 14
18AIL57- Artificial Intelligence Laboratory 2022-23

Output:
Starting work...

(12, 0, 0)
(4, 8, 0)
(0, 8, 4)
(8, 0, 4)
(8, 4, 0)
(3, 4, 5)

re
(3, 8, 1)
(11, 0, 1)
(11, 1, 0)

ge
(6, 1, 5)
(6, 6, 0)

an
av
, D
IT
M
G

Dept. Of. AIML


GMIT, Davangere 15
18AIL57- Artificial Intelligence Laboratory 2022-23

2. Implement and Demonstrate Best First Search Algorithm on any AI problem

re
ge
from queue import PriorityQueue
v=6
graph = [[] for i in range(v)]

an
def best_first_search(actual_Src, target, n):
visited = [False] * n
av
pq = PriorityQueue()
pq.put((0, actual_Src))
visited[actual_Src] = True
D

while pq.empty() == False:


u = pq.get()[1]
,

print(u, end=" ")


IT

if u == target:
break
for v, c in graph[u]:
M

if visited[v] == False:
visited[v] = True
pq.put((c, v))
G

print()

def addedge(x, y, cost):


graph[x].append((y, cost))
graph[y].append((x, cost))

Dept. Of. AIML


GMIT, Davangere 16
18AIL57- Artificial Intelligence Laboratory 2022-23

addedge(0, 1, 3)
addedge(0, 2, 6)
addedge(1, 3, 2)
addedge(1, 4, 7)
addedge(2, 5, 9)

source = 0
target = 5

re
best_first_search(source, target, v)

Output

ge
013245

Tracing of the above program

an
from queue import PriorityQueue
v=6
graph = [[] for i in range(v)]
av
def best_first_search(actual_Src, target, n):
print("actual_src", actual_Src)
print("target", target)
D

print("n", n)
visited = [False] * n
pq = PriorityQueue()
pq.put((0, actual_Src))
,
IT

visited[actual_Src] = True
print("visited:", visited[actual_Src])
print("graph", graph)
M

while pq.empty() == False:


u = pq.get()[1]
G

#print("u", u)
# Displaying the path having lowest cost
print(u, end=" ")
if u == target:
break
for v, c in graph[u]:

Dept. Of. AIML


GMIT, Davangere 17
18AIL57- Artificial Intelligence Laboratory 2022-23

print("visited[v]", visited[v])
if visited[v] == False:
visited[v] = True
pq.put((c, v))
print("vertex=",v,",","cost=",c)
print()
def addedge(x, y, cost):
print("x =", x,",", "y =", y)
graph[x].append((y, cost))

re
graph[y].append((x, cost))
print("graph array ...")
addedge(0, 1, 3)

ge
addedge(0, 2, 6)
addedge(1, 3, 2)
addedge(1, 4, 7)

an
addedge(2, 5, 9)
source = 0
target = 5
best_first_search(source, target, v)
av
output:
, D
IT
M
G

Dept. Of. AIML


GMIT, Davangere 18
18AIL57- Artificial Intelligence Laboratory 2022-23

3. Implement AO* search algorithm

re
ge
def recAOStar(n):
global finalPath
print("Expanding Node:",n)
and_nodes = []
or_nodes =[]
an
av
if(n in allNodes):
if 'AND' in allNodes[n]:
and_nodes = allNodes[n]['AND']
D

if 'OR' in allNodes[n]:
or_nodes = allNodes[n]['OR']
if len(and_nodes)==0 and len(or_nodes)==0:
,

return
IT

solvable = False
marked ={}
M

while not solvable:


if len(marked)==len(and_nodes)+len(or_nodes):
G

min_cost_least,min_cost_group_least =
least_cost_group(and_nodes,or_nodes,{})
solvable = True
change_heuristic(n,min_cost_least)
optimal_child_group[n] = min_cost_group_least

Dept. Of. AIML


GMIT, Davangere 19
18AIL57- Artificial Intelligence Laboratory 2022-23

continue
min_cost,min_cost_group = least_cost_group(and_nodes,or_nodes,marked)
is_expanded = False
if len(min_cost_group)>1:
if(min_cost_group[0] in allNodes):
is_expanded = True
recAOStar(min_cost_group[0])
if(min_cost_group[1] in allNodes):
is_expanded = True

re
recAOStar(min_cost_group[1])
else:
if(min_cost_group in allNodes):

ge
is_expanded = True
recAOStar(min_cost_group)
if is_expanded:

an
min_cost_verify, min_cost_group_verify = least_cost_group(and_nodes,
or_nodes, {})
if min_cost_group == min_cost_group_verify:
solvable = True
av
change_heuristic(n, min_cost_verify)
optimal_child_group[n] = min_cost_group
else:
D

solvable = True
change_heuristic(n, min_cost)
optimal_child_group[n] = min_cost_group
marked[min_cost_group]=1
,
IT

return heuristic(n)

def least_cost_group(and_nodes, or_nodes, marked):


M

node_wise_cost = {}
for node_pair in and_nodes:
if not node_pair[0] + node_pair[1] in marked:
G

cost = 0
cost = cost + heuristic(node_pair[0]) + heuristic(node_pair[1]) + 2
node_wise_cost[node_pair[0] + node_pair[1]] = cost
for node in or_nodes:
if not node in marked:
cost = 0

Dept. Of. AIML


GMIT, Davangere 20
18AIL57- Artificial Intelligence Laboratory 2022-23

cost = cost + heuristic(node) + 1


node_wise_cost[node] = cost
min_cost = 999999
min_cost_group = None
for costKey in node_wise_cost:
if node_wise_cost[costKey] < min_cost:
min_cost = node_wise_cost[costKey]
min_cost_group = costKey
return [min_cost, min_cost_group]

re
def heuristic(n):
return H_dist[n]

ge
def change_heuristic(n, cost):
H_dist[n] = cost

an
return

def print_path(node):
print(optimal_child_group[node], end="")
av
node = optimal_child_group[node]
if len(node) > 1:
if node[0] in optimal_child_group:
D

print("->", end="")
print_path(node[0])
if node[1] in optimal_child_group:
print("->", end="")
,
IT

print_path(node[1])
else:
if node in optimal_child_group:
M

print("->", end="")
print_path(node)
H_dist = {
G

'A': -1,
'B': 4,
'C': 2,
'D': 3,
'E': 6,
'F': 8,

Dept. Of. AIML


GMIT, Davangere 21
18AIL57- Artificial Intelligence Laboratory 2022-23

'G': 2,
'H': 0,
'I': 0,
'J': 0
}
allNodes = {
'A': {'AND': [('C', 'D')], 'OR': ['B']},
'B': {'OR': ['E', 'F']},
'C': {'OR': ['G'], 'AND': [('H', 'I')]},

re
'D': {'OR': ['J']}
}
optimal_child_group = {}

ge
optimal_cost = recAOStar('A')
print('Nodes which gives optimal cost are')
print_path('A')

an
print('\nOptimal Cost is :: ', optimal_cost)

Output:
Expanding Node: A
av
Expanding Node: B
Expanding Node: C
Expanding Node: D
D

Nodes which gives optimal cost are


CD->HI->J
Optimal Cost is :: 5
,
IT
M
G

Dept. Of. AIML


GMIT, Davangere 22
18AIL57- Artificial Intelligence Laboratory 2022-23

4. Solve 8-Queens problem with suitable assumptions


# Taking number of queens as input from user
print ("Enter the number of queens")
N = int(input())
# here we create a chessboard
# NxN matrix with all elements set to 0
board = [[0]*N for _ in range(N)]
def attack(i, j):
#checking vertically and horizontally

re
for k in range(0,N):
if board[i][k]==1 or board[k][j]==1:
return True

ge
#checking diagonally
for k in range(0,N):
for l in range(0,N):

an
if (k+l==i+j) or (k-l==i-j):
if board[k][l]==1:
return True
return False
av
def N_queens(n):
if n==0:
return True
D

for i in range(0,N):
for j in range(0,N):
if (not(attack(i,j))) and (board[i][j]!=1):
board[i][j] = 1
,
IT

if N_queens(n-1)==True:
return True
board[i][j] = 0
M

return False
N_queens(N)
for i in board:
G

print (i)

Dept. Of. AIML


GMIT, Davangere 23
18AIL57- Artificial Intelligence Laboratory 2022-23

Output

re
ge
an
av
, D
IT
M
G

Dept. Of. AIML


GMIT, Davangere 24
18AIL57- Artificial Intelligence Laboratory 2022-23

5. Implementation of TSP using heuristic approach


from sys import maxsize
from itertools import permutations
V=4
def travellingSalesmanProblem(graph, s):
vertex = []
for i in range(V):
if i != s:

re
vertex.append(i)
min_path = maxsize
next_permutation=permutations(vertex)

ge
for i in next_permutation:
current_pathweight = 0
k=s

an
for j in i:
current_pathweight += graph[k][j]
k=j
current_pathweight += graph[k][s]
av
min_path = min(min_path, current_pathweight)
return min_path
D

if __name__ == "__main__":
graph = [[0, 10, 15, 20], [10, 0, 35, 25],
[15, 35, 0, 30], [20, 25, 30, 0]]
s=0
,
IT

print(travellingSalesmanProblem(graph, s))

Output:
M

80
G

Dept. Of. AIML


GMIT, Davangere 25
18AIL57- Artificial Intelligence Laboratory 2022-23

6. Implement problem solving strategies using forward chaining

global facts
global is_changed

is_changed = True
facts = [["plant","mango"],["eating","mango"],["seed","sprouts"]]

def assert_fact(fact):

re
global facts
global is_changed
if not fact in facts:

ge
facts += [fact]
is_changed = True

an
while is_changed:
is_changed = False
for A1 in facts:
if A1[0] == "seed":
av
assert_fact(["plant",A1[1]])
if A1[0] == "plant":
assert_fact(["fruit",A1[1]])
D

if A1[0] == "plant" and ["eating",A1[1]] in facts:


assert_fact(["human",A1[1]])

print(facts)
,
IT

Output :
M
G

Dept. Of. AIML


GMIT, Davangere 26
18AIL57- Artificial Intelligence Laboratory 2022-23

7) Implement resolution principle on FOPL related problems:

import re
def dnf(formula):
# Base case: If the formula is a literal, return it as is
if re.fullmatch(r'[A-Z]|~[A-Z]|()""', formula):
return formula
# Recursive case: If the formula is a compound statement, convert it to DNF

re
if 'and' in formula or 'or' in formula:
# Split the formula into its component parts
parts = re.split(r'(?<=[^\w])or(?=[^\w])|(?<=[^\w])and(?=[^\w])',formula)

ge
print(f"parts: {parts}")
# Convert each part to DNF
dnf_parts = [dnf(part) for part in parts]

an
print(f"dnf_parts: {dnf_parts}")
# Combine the parts using the appropriate logical operator
if 'or' in formula:
return " or ".join(parts)
av
elif 'and' in formula:
return " and ".join(parts)
# Example usage
D

formula = "(A and B) or B"


dnf_formula = dnf(formula)
print(dnf_formula) # Outputs: "A or C or B or D or"
import re
,
IT

def cnf(formula):
# Base case: If the formula is a literal, return it as is
if re.fullmatch(r'[A-Z]|~[A-Z]', formula):
M

return formula
# Recursive case: If the formula is a compound statement, convert it to CNF
if 'and' in formula or 'or' in formula:
G

# Split the formula into its component parts


parts = re.split(r'(?<=\()or(?=\))|(?<=\()and(?=\))', formula)
# Convert each part to CNF
# cnf_parts = [cnf(part) for part in parts]
# Combine the parts using the appropriate logical operator
if 'and' in formula:

Dept. Of. AIML


GMIT, Davangere 27
18AIL57- Artificial Intelligence Laboratory 2022-23

return " and ".join(parts)


elif 'or' in formula:
return " or ".join(parts)
# Example usage
formula = "(A and B) or (C and D)"
cnf_formula = cnf(formula)
print(cnf_formula) # Outputs: "A and B or C and D or"

Output :

re
ge
an
av
, D
IT
M
G

Dept. Of. AIML


GMIT, Davangere 28
18AIL57- Artificial Intelligence Laboratory 2022-23

8. Implement any game and demonstrate the game playing strategies

Flames game

def remove_match_char(list1, list2):

for i in range(len(list1)):
for j in range(len(list2)):

re
if list1[i] == list2[j]:
c = list1[i]
list1.remove(c)

ge
list2.remove(c)
list3 = list1 + ["*"] + list2
return [list3, True]

an
list3 = list1 + ["*"] + list2
return [list3, False]

if __name__ == "__main__":
av
p1 = input("Player 1 name : ")
p1 = p1.lower()
p1.replace(" ", "")
D

p1_list = list(p1)
p2 = input("Player 2 name : ")
p2 = p2.lower()
p2.replace(" ", "")
,
IT

p2_list = list(p2)
proceed = True
while proceed:
M

ret_list = remove_match_char(p1_list, p2_list)


con_list = ret_list[0]
proceed = ret_list[1]
G

star_index = con_list.index("*")
p1_list = con_list[: star_index]
p2_list = con_list[star_index + 1:]
count = len(p1_list) + len(p2_list)
result = ["Friends", "Love", "Affection", "Marriage", "Enemy", "Siblings"]
while len(result) > 1:

Dept. Of. AIML


GMIT, Davangere 29
18AIL57- Artificial Intelligence Laboratory 2022-23

split_index = (count % len(result) - 1)


if split_index >= 0:
right = result[split_index + 1:]
left = result[: split_index]
result = right + left
else:
result = result[: len(result) - 1]
print("Relationship status :", result[0])

re
ge
an
av
, D
IT
M
G

Dept. Of. AIML


GMIT, Davangere 30

You might also like