Artificial Intelligence lab

WELCOME TO EXAMHELPER20

CREATED BY "NIKHIL DOPPANI"


DO FOLLOW examhelper20


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:")

    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 AITS-R")

    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")


 

Depth first search (DFS)

graph = {
  '5' : ['3','7'],
  '3' : ['2', '4'],
  '7' : ['8'],
  '2' : [],
  '4' : ['8'],
  '8' : []
}

visited = set()

def dfs(visited, graph, node):
    if node not in visited:
        print (node)
        visited.add(node)
        for neighbour in graph[node]:
            dfs(visited, graph, neighbour)

print("Following is the Depth-First Search")
dfs(visited, graph, '5')



MAGIC SQUARE:

def generateSquare(n):
	magicSquare = [[0 for x in range(n)]
		for y in range(n)]

	i = n // 2
	j = n - 1

	num = 1
	while num <= (n * n):
		if i == -1 and j == n: 
			j = n - 2
			i = 0
		else:

			if j == n:
				j = 0

			if i < 0:
				i = n - 1

		if magicSquare[int(i)][int(j)]: # 2nd condition
			j = j - 2
			i = i + 1
			continue
		else:
			magicSquare[int(i)][int(j)] = num
			num = num + 1

		j = j + 1
		i = i - 1 

	print("Magic Square for n =", n)
	print("Sum of each row or column",
		n * (n * n + 1) // 2, "\n")

	for i in range(0, n):
		for j in range(0, n):
			print('%2d ' % (magicSquare[i][j]),end='')

			if j == n - 1:
				print()
n = 7
generateSquare(n)


8 PUZZLE:

def solve(self, board):
dict = {}
flatten = []
for i in range(len(board)):
flatten += board[i]
flatten = tuple(flatten)
dict[flatten] = 0
if flatten == (0, 1, 2, 3, 4, 5, 6, 7, 8):
return 0
return self.get_paths(dict)
def get_paths(self, dict):
cnt = 0
while True:
current_nodes = [x for x in dict if dict[x] == cnt]
if len(current_nodes) == 0:
return -1
for node in current_nodes:
next_moves = self.find_next(node)
for move in next_moves:
if move not in dict:
dict[move] = cnt + 1
if move == (0, 1, 2, 3, 4, 5, 6, 7, 8):
return cnt + 1
cnt += 1
def find_next(self, node):
moves = {
0: [1, 3],
1: [0, 2, 4],
2: [1, 5],
3: [0, 4, 6],
4: [1, 3, 5, 7],
5: [2, 4, 8],
6: [3, 7],
7: [4, 6, 8],
8: [5, 7],
}
results = []
pos_0 = node.index(0)
for move in moves[pos_0]:
new_node = list(node)
new_node[move], new_node[pos_0] = new_node[pos_0], new_node[move]
results.append(tuple(new_node))
return results
ob = Solution()
matrix = [
[3, 1, 2],
[4, 7, 5],
[6, 8, 0]]



CRYTARITHMETIC:

def isSolvable(words, result):
	mp = [-1]*(26)
	used = [0]*(10)
	Hash = [0]*(26)
	CharAtfront = [0]*(26)
	uniq = ""
	for word in range(len(words)):
		for i in range(len(words[word])):
			ch = words[word][i]
			Hash[ord(ch) - ord('A')] += pow(10, len(words[word]) - i - 1)
			if mp[ord(ch) - ord('A')] == -1:
				mp[ord(ch) - ord('A')] = 0
				uniq += str(ch)
			if i == 0 and len(words[word]) > 1:
				CharAtfront[ord(ch) - ord('A')] = 1
	for i in range(len(result)):
		ch = result[i]
		Hash[ord(ch) - ord('A')] -= pow(10, len(result) - i - 1)
		if mp[ord(ch) - ord('A')] == -1:
			mp[ord(ch) - ord('A')] = 0
			uniq += str(ch)
		if i == 0 and len(result) > 1:
			CharAtfront[ord(ch) - ord('A')] = 1
	mp = [-1]*(26)
	return True
def solve(words, i, S, mp, used, Hash, CharAtfront):
	if i == len(words):
		return S == 0
	ch = words[i]
	val = mp[ord(words[i]) - ord('A')]
	if val != -1:
		return solve(words, i + 1, S + val * Hash[ord(ch) - ord('A')], mp, used, Hash, CharAtfront)
	x = False
	for l in range(10):
		if CharAtfront[ord(ch) - ord('A')] == 1 and l == 0:
			continue
		if used[l] == 1:
			continue
		mp[ord(ch) - ord('A')] = l
		used[l] = 1
		x |= solve(words, i + 1, S + l * Hash[ord(ch) - ord('A')], mp, used, Hash, CharAtfront)
		mp[ord(ch) - ord('A')] = -1
		used[l] = 0
	return x
arr = [ "SIX", "SEVEN", "SEVEN" ]
S = "TWENTY"
if isSolvable(arr, S):
	print("Yes")
else:
	print("No")



HILL CLIMBING:

import random
def randomSolution(tsp):
    cities = list(range(len(tsp)))
    solution = []
    for i in range(len(tsp)):
        randomCity = cities[random.randint(0, len(cities) - 1)]
        solution.append(randomCity)
        cities.remove(randomCity)
    return solution
def routeLength(tsp, solution):
    routeLength = 0
    for i in range(len(solution)):
        routeLength += tsp[solution[i - 1]][solution[i]]
    return routeLength
def getNeighbours(solution):
    neighbours = []
    for i in range(len(solution)):
        for j in range(i + 1, len(solution)):
            neighbour = solution.copy()
            neighbour[i] = solution[j]
            neighbour[j] = solution[i]
            neighbours.append(neighbour)
    return neighbours
def getBestNeighbour(tsp, neighbours):
    bestRouteLength = routeLength(tsp, neighbours[0])
    bestNeighbour = neighbours[0]
    for neighbour in neighbours:
        currentRouteLength = routeLength(tsp, neighbour)
        if currentRouteLength < bestRouteLength:
            bestRouteLength = currentRouteLength
            bestNeighbour = neighbour
    return bestNeighbour, bestRouteLength
def hillClimbing(tsp):
    currentSolution = randomSolution(tsp)
    currentRouteLength = routeLength(tsp, currentSolution)
    neighbours = getNeighbours(currentSolution)
    bestNeighbour, bestNeighbourRouteLength = getBestNeighbour(tsp, neighbours)
    while bestNeighbourRouteLength < currentRouteLength:
        currentSolution = bestNeighbour
        currentRouteLength = bestNeighbourRouteLength
        neighbours = getNeighbours(currentSolution)
        bestNeighbour, bestNeighbourRouteLength = getBestNeighbour(tsp, neighbours)
    return currentSolution, currentRouteLength
def main():
    tsp = [
        [0, 400, 500, 300],
        [400, 0, 300, 500],
        [500, 300, 0, 400],
        [300, 500, 400, 0]
    ]
    print(hillClimbing(tsp))
    
if __name__ == "__main__":
    main()



WATER JUG:

j1 = 0 
j2 = 0 
x = 4
y = 3
print("Initial state = (0,0)")
print("Capacities = (4,3)")
print("Goal state = (2,y)")
while j1 != 2:
  r = int(input("Enter rule"))
  if(r == 1):
    j1 = x
  elif(r == 2):
    j2 = y
  elif(r == 3):
    j1 = 0
  elif(r == 4):
    j2 = 0
  elif(r == 5):
    t = x - j1
    j1 = x
    j2 = j2-t
    if(j2<0):
        j2=0
  elif(r == 6):
    t = y - j2
    j2 = y
    j1 = j1-t
    if(j1<0):
        j1=0
  elif(r == 7):
    j1 = j1+j2
    j2 = 0
    if(j1>x):
        j1=x
  elif(r == 8):
    j2 = j1+j2
    j1 = 0
    if(j2>y):
        j2=y
  print(j1,j2)



Comments

Popular posts from this blog