0% found this document useful (0 votes)
3 views10 pages

Program AI Merged

Uploaded by

talkwithhexa420
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)
3 views10 pages

Program AI Merged

Uploaded by

talkwithhexa420
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

Experiment 1:

Program
# Simple Movie Recommendation using Similarity

movies = {
"User1": [5, 4, 0, 0, 3],
"User2": [4, 0, 0, 2, 3],
"User3": [0, 3, 4, 0, 5],
}

import numpy as np

def cosine_similarity(a, b):


return [Link](a, b) / ([Link](a) * [Link](b))

print("Similarity between User1 and User2:",


cosine_similarity(movies["User1"], movies["User2"]))

Output
Similarity between User1 and User2: 0.78
Experiment 2:

Program
# State Space and PEAS Representation Example

print("State Space Representation - Vacuum Cleaner Problem")


print("Initial State: Room is Dirty")
print("Actions: Move Left, Move Right, Suck")
print("Goal State: Room is Clean")

print("\nPEAS Representation:")
print("Performance: Cleanliness, Time Efficiency")
print("Environment: Rooms A and B")
print("Actuators: Move Left, Move Right, Suck")
print("Sensors: Dirt Sensor, Location Sensor")

Output
State Space Representation - Vacuum Cleaner Problem
Initial State: Room is Dirty
Actions: Move Left, Move Right, Suck
Goal State: Room is Clean

PEAS Representation:
Performance: Cleanliness, Time Efficiency
Environment: Rooms A and B
Actuators: Move Left, Move Right, Suck
Sensors: Dirt Sensor, Location Sensor
Experiment 3:

Program

from collections import deque

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

# Breadth First Search


def bfs(start):
visited = set()
queue = deque([start])
print("BFS Traversal:", end=" ")

while queue:
node = [Link]()
if node not in visited:
print(node, end=" ")
[Link](node)
[Link](graph[node])

# Depth First Search


def dfs(start, visited=None):
if visited is None:
visited = set()
print(start, end=" ")
[Link](start)

for neighbor in graph[start]:


if neighbor not in visited:
dfs(neighbor, visited)

# Function Calls
bfs('A')
print("\nDFS Traversal:", end=" ")
dfs('A')

Output
BFS Traversal: A B C D E F
DFS Traversal: A B D E C F
Experiment 4:

Program (A* Search – Simple Graph Example)

import heapq

graph = {
'A': [('B', 1), ('C', 3)],
'B': [('D', 3), ('E', 1)],
'C': [('F', 5)],
'D': [],
'E': [('G', 2)],
'F': [],
'G': []
}

heuristic = {
'A': 7, 'B': 6, 'C': 5,
'D': 3, 'E': 2, 'F': 6,
'G': 0
}

def a_star(start, goal):


pq = []
[Link](pq, (heuristic[start], start))
visited = set()

while pq:
cost, node = [Link](pq)

if node == goal:
print("Goal reached:", node)
return

if node not in visited:


print("Visited:", node)
[Link](node)

for neighbor, g_cost in graph[node]:


if neighbor not in visited:
f_cost = g_cost + heuristic[neighbor]
[Link](pq, (f_cost, neighbor))

a_star('A', 'G')
Output

Visited: A
Visited: B
Visited: E
Goal reached: G
Experiment 5:

Program (Min max Algorithm – Simple Example)


def minimax(depth, is_max):
# Terminal condition
if depth == 0:
return 1

if is_max:
best = -1000
for i in range(2):
value = minimax(depth - 1, False)
best = max(best, value)
return best
else:
best = 1000
for i in range(2):
value = minimax(depth - 1, True)
best = min(best, value)
return best

# Driver code
print("Optimal value using Minimax:", minimax(3, True))
Output

Optimal value using Minimax: 1


Experiment 6:

Program (Simple FOL Representation Using Python)

# First Order Logic Representation Example

def human(x):
return x == "Socrates"

def mortal(x):
if human(x):
return True
return False

person = "Socrates"

if mortal(person):
print(person, "is Mortal")
else:
print(person, "is not Mortal")
Output

Socrates is Mortal
Experiment 7:

Program (Simple Automated Planning Example in Python)


# Simple Automated Planning Example

initial_state = "Room Dirty"


goal_state = "Room Clean"

actions = {
"Clean": {
"precondition": "Room Dirty",
"effect": "Room Clean"
}
}

print("Initial State:", initial_state)

if initial_state == actions["Clean"]["precondition"]:
initial_state = actions["Clean"]["effect"]
print("Action Performed: Clean")

print("Final State:", initial_state)


Output

Initial State: Room Dirty


Action Performed: Clean
Final State: Room Clean
Experiment 8:

Program (Simple Bayesian Reasoning Example in Python)


# Bayesian Belief Network Example

# Prior probability of Rain


P_rain = 0.3

# Conditional probability of Traffic given Rain


P_traffic_given_rain = 0.8

# Calculating joint probability


P_rain_and_traffic = P_rain * P_traffic_given_rain

print("Probability of rain:", P_rain)


print("Probability of traffic given rain:", P_traffic_given_rain)
print("Probability of traffic due to rain:", P_rain_and_traffic)

Output
Probability of rain: 0.3
Probability of traffic given rain: 0.8
Probability of traffic due to rain: 0.24
PROGRAM:

import math
labels = ['A', 'D', 'F', 'G', 'V', 'X']
# -------- Build ADFGVX Polybius Matrix using Key-1 --------
defbuild_polybius(key):
key = [Link]()
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
used = []
forch in key:
ifch not in used and ch in alphabet:
[Link](ch)
forch in alphabet:
ifch not in used:
[Link](ch)

matrix = []
idx = 0
for _ in range(6):
[Link](used[idx:idx+6])
idx += 6
return matrix
# -------- ADFGVX Substitution --------
defadfgvx_substitution(plaintext, matrix):
plaintext = [Link]().replace(" ", "")
result = []

forch in plaintext:
found = False
for i in range(6):
for j in range(6):
if matrix[i][j] == ch:
[Link](labels[i] + labels[j])
found = True
break
if found:
break
return " ".join(result)
# -------- Single Columnar Transposition --------
defcolumnar_transposition(text, key):
text = [Link](" ", "")
key = [Link]()
cols = len(key)
rows = [Link](len(text) / cols)
# Pad only for matrix filling
padded = text + 'X' * (rows * cols - len(text))

# Fill matrix row-wise


matrix = []
idx = 0
for _ in range(rows):
[Link](list(padded[idx:idx+cols]))
idx += cols
# Read columns in alphabetical order of key
order = sorted(range(len(key)), key=lambda k: key[k])
cipher = ""
for col in order:
for row in matrix:
cipher += row[col]

# Remove padding X characters


cipher = [Link]('X', '')

# Group into blocks of 3


return " ".join(cipher[i:i+3] for i in range(0, len(cipher), 3))

# -------- Driver Code --------


plain = input("Enter plaintext: ")
key1 = input("Enter first key (Polybius key): ")
key2 = input("Enter second key (Transposition key): ")
polybius = build_polybius(key1)
intermediate = adfgvx_substitution(plain, polybius)
print("Intermediate Cipher Text:", intermediate)

final_cipher = columnar_transposition(intermediate, key2)


print("Final Ciphertext:", final_cipher)
OUTPUT:
Enter plaintext: COMPUTER
Enter first key (Polybius key): LEMON
Enter second key (Transposition key): BREAD
Intermediate Cipher Text: DD AG AF FG GF GD AD FX
Final Ciphertext: GGD DFG AFF AGA DFD

You might also like