AI Lab

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

1. Write a python program to implement Breadth First Search Traversal.

# Python3 Program to print BFS traversal


# from a given source vertex. BFS(int s)
# traverses vertices reachable from s.
from collections import defaultdict

# This class represents a directed graph


# using adjacency list representation
class Graph:

# Constructor
def __init__(self):

# default dictionary to store graph


self.graph = defaultdict(list)

# function to add an edge to graph


# Make a list visited[] to check if a node is already visited or not
def addEdge(self,u,v):
self.graph[u].append(v)
self.visited=[]
# Function to print a BFS of graph
def BFS(self, s):

# Create a queue for BFS


queue = []

# Add the source node in


# visited and enqueue it
queue.append(s)
self.visited.append(s)

while queue:

# Dequeue a vertex from


# queue and print it
s = queue.pop(0)
print (s, end = " ")

# Get all adjacent vertices of the


# dequeued vertex s. If a adjacent
# has not been visited, then add it
# in visited and enqueue it
for i in self.graph[s]:
if i not in visited:
queue.append(i)
self.visited.append(s)

# Driver code
# Create a graph given in
# the above diagram
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)

print ("Following is Breadth First Traversal"


" (starting from vertex 2)")
g.BFS(2)

2. Write a python program to implement Water Jug Problem

# This function is used to initialize the


# dictionary elements with a default value.
from collections import defaultdict

# jug1 and jug2 contain the value


# for max capacity in respective jugs
# and aim is the amount of water to be measured.
jug1, jug2, aim = 4, 3, 2

# Initialize dictionary with


# default value as false.
visited = defaultdict(lambda: False)

# Recursive function which prints the


# intermediate steps to reach the final
# solution and return boolean value
# (True if solution is possible, otherwise False).
# amt1 and amt2 are the amount of water present
# in both jugs at a certain point of time.
def waterJugSolver(amt1, amt2):

# Checks for our goal and


# returns true if achieved.
if (amt1 == aim and amt2 == 0) or (amt2 == aim and amt1 == 0):
print(amt1, amt2)
return True

# Checks if we have already visited the


# combination or not. If not, then it proceeds further.
if visited[(amt1, amt2)] == False:
print(amt1, amt2)

# Changes the boolean value of


# the combination as it is visited.
visited[(amt1, amt2)] = True
# Check for all the 6 possibilities and
# see if a solution is found in any one of them.
return (waterJugSolver(0, amt2) or
waterJugSolver(amt1, 0) or
waterJugSolver(jug1, amt2) or
waterJugSolver(amt1, jug2) or
waterJugSolver(amt1 + min(amt2, (jug1-amt1)),
amt2 - min(amt2, (jug1-amt1))) or
waterJugSolver(amt1 - min(amt1, (jug2-amt2)),
amt2 + min(amt1, (jug2-amt2))))

# Return False if the combination is


# already visited to avoid repetition otherwise
# recursion will enter an infinite loop.
else:
return False

print("Steps: ")

# Call the function and pass the


# initial amount of water present in both jugs.
waterJugSolver(0, 0)

3. Write a python program to remove punctuations from the given string

# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

my_str = "Hello!!!, he said ---and went."

# To take input from the user


# my_str = input("Enter a string: ")

# remove punctuation from the string


no_punct = ""
for char in my_str:
if char not in punctuations:
no_punct = no_punct + char

# display the unpunctuated string


print(no_punct)

4. Write a python program to sort the sentence in alphabetical order

Using sorted()

# Python3 program to sort the words of a string in


# alphabetical order
# Function to sort the words in alphabetical order
def Func(S):
W = S.split(" ")
for i in range(len(W)):

# convert all the words into lowercase


W[i]=W[i].lower()
S = sorted(W)
print(' '.join(S))

# Driver code
S = "the Quick brown fox jumPs over the lazY Dog"

# function call
Func(S)

Using sort()
# Python3 program to sort the words of a
# string in alphabetical order

# Function to sort the words in alphabetical


# order
def F(S):
W = S.split(" ")
for i in range(len(W)):
W[i] = W[i].lower()
W.sort()

# return the sorted words


return ' '.join(W)

# Driver code
S = "GeekS for geEks"
print(F(S))

Using insertion sort:

def sort_words_alphabetically(input_string):
words = input_string.split()
n = len(words)
for i in range(1, n):
key = words[i]
j = i - 1
while j >= 0 and words[j] > key:
words[j+1] = words[j]
j -= 1
words[j+1] = key
return ' '.join(words)

input_string = 'the Quick brown fox jumPs over the lazY Dog'
output_string = sort_words_alphabetically(input_string)
print(output_string)

5. Write a program to implement Hangman game using python.

import random

def get_random_word_from_wordlist():
wordlist = []

with open("hangman_wordlist.txt", 'r') as file:


wordlist = file.read().split("\n")

word = random.choice(wordlist)
return word

def get_some_letters(word):
letters = []
temp = '_' * len(word)

for char in list(word):


if char not in letters:
letters.append(char)

character = random.choice(letters)

for num, char in enumerate(list(word)):


if char == character:
templist = list(temp)
templist[num] = char
temp = ''.join(templist)

return temp

def draw_hangman(chances):
if chances == 6:
print("________ ")
print("| | ")
print("| ")
print("| ")
print("| ")
print("| ")
elif chances == 5:
print("________ ")
print("| | ")
print("| 0 ")
print("| ")
print("| ")
print("| ")
elif chances == 4:
print("________ ")
print("| | ")
print("| 0 ")
print("| / ")
print("| ")
print("| ")
elif chances == 3:
print("________ ")
print("| | ")
print("| 0 ")
print("| /| ")
print("| ")
print("| ")
elif chances == 2:
print("________ ")
print("| | ")
print("| 0 ")
print("| /|\ ")
print("| ")
print("| ")
elif chances == 1:
print("________ ")
print("| | ")
print("| 0 ")
print("| /|\ ")
print("| / ")
print("| ")
elif chances == 0:
print("________ ")
print("| | ")
print("| 0 ")
print("| /|\ ")
print("| / \ ")
print("| ")
def start_hangman_game():
word = get_random_word_from_wordlist()
temp = get_some_letters(word)
chances = 7
found = False
while True:
if chances == 0:
print(f"Sorry! You Lost, the word was: {word}")
print("Better luck next time")
break

print("=== Guess the word ===")


print(temp, end='')
print(f"\t(word has {len(word)} letters)")
print(f"Chances left: {chances}")
character = input("Enter the character you think the word may have: ")

if len(character) > 1 or not character.isalpha():


print("Please enter a single alphabet only")
continue
else:
for num, char in enumerate(list(word)):
if char == character:
templist = list(temp)
templist[num] = char
temp = ''.join(templist)
found = True

if found:
found = False
else:
chances -= 1

if '_' not in temp:


print(f"\nYou Won! The word was: {word}")
print(f"You got it in {7 - chances} guess")
break
else:
draw_hangman(chances)

print()
print("===== Welcome to the Hangman Game =====")

while True:
choice = input("Do you wanna play hangman? (yes/no): ")

if 'yes' in choice.lower():
start_hangman_game()
elif 'no' in choice.lower():
print('Quitting the game...')
break
else:
print("Please enter a valid choice.")

print("\n")

You might also like