Lab Programs.
Lab Programs.
Lab Programs.
BFS PROGRAM
for i in graph[s]:
#print(graph[s])
if i not in visited:
visited.append(i)
#print(visited)
queue.append(i)
# Driver Code
bfs(visited, graph, "b")
2.DFS PROGRAM
# Driver Code
dfs(visited, graph, "a")
3.WATER JUG PROBLEM
#here we are using default dict which is used to initialize the dict elements with
default value
from collections import defaultdict
#jug1 and jug2 have the max capacity of two jugs and target is the amount to be
measured
# Recursive function which prints the intermediate steps to reach the final
# solution and return boolean value (True if solution is possible, otherwise
False).
# amountt1 and amount2 are the amount of water present in both jugs at a certain
point of time.
def waterjugProblem(amount1, amount2):
print("Steps: ")
def main():
for state in states:
colors_of_states[state] = get_color_for_state(state)
print (colors_of_states)
main()
for j in i:
print('j=',j)
current_pathweight += graph[k][j]
print('current_pathweight1=',current_pathweight)
k = j
print('k=',k)
current_pathweight += graph[k][s]
print('graph[k][s]=',graph[k][s])
print('current_pathweight2=',current_pathweight)
# update minimum
min_path = min(min_path, current_pathweight)
return min_path
# Driver Code
if __name__ == "__main__":
6. 8 QUEENS PROBLEM
#Number of queens
print ("Enter the number of queens")
N = int(input())
#chessboard
#NxN matrix with all elements 0
board = [[0]*N for _ in range(N)]
print(board)
def is_attack(i, j):
#checking if there is a queen in row or column
for k in range(0,N):
if board[i][k]==1 or board[k][j]==1:
return True
#checking diagonals
for k in range(0,N):
for l in range(0,N):
if (k+l==i+j) or (k-l==i-j):
if board[k][l]==1:
return True
return False
def N_queen(n):
#if n is 0, solution found
if n==0:
return True
for i in range(0,N):
for j in range(0,N):
'''checking if we can place a queen here or not
queen will not be placed if the place is being attacked
or already occupied'''
if (not(is_attack(i,j))) and (board[i][j]!=1):
board[i][j] = 1
#recursion
#wether we can put the next queen with this arrangment or not
if N_queen(n-1)==True:
return True
board[i][j] = 0
return False
N_queen(N)
for i in board:
print (i)
import random
def drawBoard(board):
# This function prints out the board that it was passed.
def inputPlayerLetter():
# Lets the player type which letter they want to be.
# Returns a list with the player's letter as the first item, and the computer's
letter as the second.
letter = ''
while not (letter == 'X' or letter == 'O'):
print('Do you want to be X or O?')
letter = input().upper()
# the first element in the tuple is the player's letter, the second is the
computer's letter.
if letter == 'X':
return ['X', 'O']
else:
return ['O', 'X']
def whoGoesFirst():
# Randomly choose the player who goes first.
if random.randint(0, 1) == 0:
return 'computer'
else:
return 'player'
def playAgain():
# This function returns True if the player wants to play again, otherwise it
returns False.
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y')
def getBoardCopy(board):
# Make a duplicate of the board list and return it the duplicate.
dupeBoard = []
for i in board:
dupeBoard.append(i)
return dupeBoard
def getPlayerMove(board):
# Let the player type in his move.
move = ' '
while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board,
int(move)):
print('What is your next move? (1-9)')
move = input()
return int(move)
def chooseRandomMoveFromList(board, movesList):
# Returns a valid move from the passed list on the passed board.
# Returns None if there is no valid move.
possibleMoves = []
for i in movesList:
if isSpaceFree(board, i):
possibleMoves.append(i)
if len(possibleMoves) != 0:
return random.choice(possibleMoves)
else:
return None
# Check if the player could win on his next move, and block them.
for i in range(1, 10):
copy = getBoardCopy(board)
if isSpaceFree(copy, i):
makeMove(copy, playerLetter, i)
if isWinner(copy, playerLetter):
return i
def isBoardFull(board):
# Return True if every space on the board has been taken. Otherwise return
False.
for i in range(1, 10):
if isSpaceFree(board, i):
return False
return True
print('Welcome to Tic Tac Toe!')
while True:
# Reset the board
theBoard = [' '] * 10
playerLetter, computerLetter = inputPlayerLetter()
turn = whoGoesFirst()
print('The ' + turn + ' will go first.')
gameIsPlaying = True
while gameIsPlaying:
if turn == 'player':
# Player's turn.
drawBoard(theBoard)
move = getPlayerMove(theBoard)
makeMove(theBoard, playerLetter, move)
if isWinner(theBoard, playerLetter):
drawBoard(theBoard)
print('Hooray! You have won the game!')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game is a tie!')
break
else:
turn = 'computer'
else:
# Computer's turn.
move = getComputerMove(theBoard, computerLetter)
makeMove(theBoard, computerLetter, move)
if isWinner(theBoard, computerLetter):
drawBoard(theBoard)
print('The computer has beaten you! You lose.')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game is a tie!')
break
else:
turn = 'player'
if not playAgain():
break
8. HANGMAN GAME
import random
word_list = ["insert", "your", "words", "in", "this", "python", "list"]
def get_word(word_list):
word = random.choice(word_list)
return word.upper()
def play(word):
word_completion = "_" * len(word)
guessed = False
guessed_letters = []
tries = 6
print("Let's play Hangman")
print(display_hangman(tries))
print(word_completion)
print("\n")
while not guessed and tries > 0:
guess = input("guess a letter or word: ").upper()
if len(guess) == 1 and guess.isalpha():
if guess in guessed_letters:
print("you already tried", guess, "!")
elif guess not in word:
print(guess, "isn't in the word :(")
tries -= 1
guessed_letters.append(guess)
else:
print("Nice one,", guess, "is in the word!")
guessed_letters.append(guess)
word_as_list = list(word_completion)
indices = [i for i, letter in enumerate(word) if letter == guess]
for index in indices:
word_as_list[index] = guess
word_completion = "".join(word_as_list)
if "_" not in word_completion:
guessed = True
else:
print("invalid input")
print(display_hangman(tries))
print(word_completion)
print("\n")
if guessed:
print("Good Job, you guessed the word!")
else:
print("I'm sorry, but you ran out of tries. The word was " + word + ".
Maybe next time!")
def display_hangman(tries):
stages = [ """
--------
| |
| O
| \\|/
| |
| / \\
-
""",
"""
--------
| |
| O
| \\|/
| |
| /
-
""",
"""
--------
| |
| O
| \\|/
| |
|
-
""",
"""
--------
| |
| O
| \\|
| |
|
-
""",
"""
--------
| |
| O
| |
| |
|
-
""",
"""
--------
| |
| O
|
|
|
-
""",
"""
--------
| |
|
|
|
|
-
"""
]
return stages[tries]
def main():
word = get_word(word_list)
play(word)
while input("Again? (Y/N) ").upper() == "Y":
word = get_word(word_list)
play(word)
if __name__ == "__main__":
main()
SOURCE CODE:
# This class represent a graph
class Graph:
# Add a link from A and B of given distance, and also add the inverse link if the
graph is undirected
def connect(self, A, B, distance=1):
self.graph_dict.setdefault(A, {})[B] = distance
if not self.directed:
self.graph_dict.setdefault(B, {})[A] = distance
# Compare nodes
def __eq__(self, other):
return self.name == other.name
# Sort nodes
def __lt__(self, other):
return self.f < other.f
# Print node
def __repr__(self):
return ('({0},{1})'.format(self.name, self.f))
# A* search
def astar_search(graph, heuristics, start, end):
# Sort the open list to get the node with the lowest cost first
open.sort()
# Get neighbours
neighbors = graph.get(current_node.name)
# Loop neighbors
for key, value in neighbors.items():
# Create a neighbor node
neighbor = Node(key, current_node)
# Create a graph
graph = Graph()
SOURCE CODE:
class State():
def __init__(self, cannibalLeft, missionaryLeft, boat, cannibalRight,
missionaryRight):
self.cannibalLeft = cannibalLeft
self.missionaryLeft = missionaryLeft
self.boat = boat
self.cannibalRight = cannibalRight
self.missionaryRight = missionaryRight
self.parent = None
def is_goal(self):
if self.cannibalLeft == 0 and self.missionaryLeft == 0:
return True
else:
return False
def is_valid(self):
if self.missionaryLeft >= 0 and self.missionaryRight >= 0 \
and self.cannibalLeft >= 0 and self.cannibalRight >= 0 \
and (self.missionaryLeft == 0 or self.missionaryLeft >=
self.cannibalLeft) \
and (self.missionaryRight == 0 or self.missionaryRight >=
self.cannibalRight):
return True
else:
return False
def __hash__(self):
return hash((self.cannibalLeft, self.missionaryLeft, self.boat,
self.cannibalRight, self.missionaryRight))
def successors(cur_state):
children = [];
if cur_state.boat == 'left':
new_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft - 2,
'right',
cur_state.cannibalRight,
cur_state.missionaryRight + 2)
## Two missionaries cross left to right.
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft - 2, cur_state.missionaryLeft,
'right',
cur_state.cannibalRight + 2,
cur_state.missionaryRight)
## Two cannibals cross left to right.
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft - 1, cur_state.missionaryLeft
- 1, 'right',
cur_state.cannibalRight + 1,
cur_state.missionaryRight + 1)
## One missionary and one cannibal cross left to right.
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft - 1,
'right',
cur_state.cannibalRight,
cur_state.missionaryRight + 1)
## One missionary crosses left to right.
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft - 1, cur_state.missionaryLeft,
'right',
cur_state.cannibalRight + 1,
cur_state.missionaryRight)
## One cannibal crosses left to right.
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
else:
new_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft + 2,
'left',
cur_state.cannibalRight,
cur_state.missionaryRight - 2)
## Two missionaries cross right to left.
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft + 2, cur_state.missionaryLeft,
'left',
cur_state.cannibalRight - 2,
cur_state.missionaryRight)
## Two cannibals cross right to left.
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft + 1, cur_state.missionaryLeft
+ 1, 'left',
cur_state.cannibalRight - 1,
cur_state.missionaryRight - 1)
## One missionary and one cannibal cross right to left.
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft, cur_state.missionaryLeft + 1,
'left',
cur_state.cannibalRight,
cur_state.missionaryRight - 1)
## One missionary crosses right to left.
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
new_state = State(cur_state.cannibalLeft + 1, cur_state.missionaryLeft,
'left',
cur_state.cannibalRight - 1,
cur_state.missionaryRight)
## One cannibal crosses right to left.
if new_state.is_valid():
new_state.parent = cur_state
children.append(new_state)
return children
def breadth_first_search():
initial_state = State(3,3,'left',0,0)
if initial_state.is_goal():
return initial_state
frontier = list()
explored = set()
frontier.append(initial_state)
while frontier:
state = frontier.pop(0)
if state.is_goal():
return state
explored.add(state)
children = successors(state)
for child in children:
if (child not in explored) or (child not in frontier):
frontier.append(child)
return None
def print_solution(solution):
path = []
path.append(solution)
parent = solution.parent
while parent:
path.append(parent)
parent = parent.parent
for t in range(len(path)):
state = path[len(path) - t - 1]
print ("(" + str(state.cannibalLeft) + "," +
str(state.missionaryLeft) \
+ "," + state.boat + "," + str(state.cannibalRight) +
"," + \
str(state.missionaryRight) + ")")
def main():
solution = breadth_first_search()
print( "Missionaries and Cannibals solution:")
print ("(cannibalLeft,missionaryLeft,boat,cannibalRight,missionaryRight)")
print_solution(solution)
OUTPUT:
Missionaries and Cannibals solution:
(cannibalLeft,missionaryLeft,boat,cannibalRight,missionaryRight)
(3,3,left,0,0)
(1,3,right,2,0)
(2,3,left,1,0)
(0,3,right,3,0)
(1,3,left,2,0)
(1,1,right,2,2)
(2,2,left,1,1)
(2,0,right,1,3)
(3,0,left,0,3)
(1,0,right,2,3)
(1,1,left,2,2)
(0,0,right,3,3)
SOURCE CODE:
Install Pomegranate Library and watermark library
!pip install pomegranate
!pip install watermark
State objects hold both the distribution, and a high level name.
s1 = State(guest, name="guest")
s2 = State(prize, name="prize")
s3 = State(monty, name="monty")
Add edges which represent conditional dependencies, where the second node is
model.add_edge(s1, s3)
model.add_edge(s2, s3)
OUTPUT:
Predicting Probabilities
model.probability([['A', 'B', 'C']])
0.11111111111111109
model.probability([['A', 'B', 'B']])
0.0
SOURCE CODE:
import numpy as np
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
%matplotlib inline
print(q_df)
q = q_df.values
print('\n', q, q.shape, '\n')
print(q_df.sum(axis=1))
from pprint import pprint
def _get_markov_edges(Q):
edges = {}
for col in Q.columns:
for idx in Q.index:
edges[(idx,col)] = Q.loc[idx,col]
return edges
edges_wts = _get_markov_edges(q_df)
pprint(edges_wts)
OUTPUT:
sleeping 0.35
eating 0.35
pooping 0.30
Name: states, dtype: float64
1.0
sleeping eating pooping
sleeping 0.4 0.2 0.4
eating 0.45 0.45 0.1
pooping 0.45 0.25 0.3
[[0.4 0.2 0.4]
[0.45 0.45 0.1]
[0.45 0.25 0.3]] (3, 3)
sleeping 1.0
eating 1.0
pooping 1.0
dtype: float64
{('eating', 'eating'): 0.45,
('eating', 'pooping'): 0.1,
('eating', 'sleeping'): 0.45,
('pooping', 'eating'): 0.25,
('pooping', 'pooping'): 0.3,
('pooping', 'sleeping'): 0.45,
('sleeping', 'eating'): 0.2,
('sleeping', 'pooping'): 0.4,
('sleeping', 'sleeping'): 0.4}