Ai Lab 01
Ai Lab 01
Karachi Campus
COURSE:
Artificial Intelligence Lab
TERM: SPRING 2024, CLASS: BSE- 6(A)
Submitted By:
EIMA NASIR 79297
(Name) (Registration. No.)
Submitted To:
Submitted On:
[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 01]
Date: 18/02/2024
Solution:
Solution:
Solution:
Task No. 04: Create a program that counts the frequency of words in a given
text file or input string.
Output:
Output:
Solution:
def fizz_buzz():
for i in range(1, 101):
if i % 3 == 0 and i % 5 == 0:
print("Fizz Buzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
if __name__ == "__main__":
fizz_buzz()
Output:
Solution:
Solution:
import random
def choose_word():
words = ['apple', 'banana', 'orange', 'grape', 'pear', 'kiwi', 'melon', 'strawberry',
'blueberry', 'pineapple']
return random.choice(words)
def display_word(word, guessed_letters):
displayed = ''
for letter in word:
if letter in guessed_letters:
displayed += letter
else:
displayed += '_'
return displayed
def hangman():
word = choose_word()
guessed_letters = []
attempts = 7
print("Welcome to Hangman!")
print("Try to guess the word in less than 7 attempts.")
print(display_word(word, guessed_letters))
while attempts > 0:
guess = input("Enter a letter: ").lower()
if len(guess) != 1 or not guess.isalpha():
print("Please enter a single letter.")
continue
if guess in guessed_letters:
print("You already guessed that letter.")
continue
guessed_letters.append(guess)
if guess not in word:
attempts -= 1
print(f"Incorrect! You have {attempts} attempts left.")
else:
print("Correct guess!")
displayed_word = display_word(word, guessed_letters)
print(displayed_word)
if '_' not in displayed_word:
print("Congratulations! You've guessed the word correctly!")
break
if '_' in displayed_word:
print(f"Sorry, you're out of attempts. The word was '{word}'.")
if __name__ == "__main__":
hangman()
bt
Task No. 08: Implement the classic game of Hangman where the user has to
guess a word by suggesting letters within a certain number of attempts.
Solution:
def read_data(file_path):
try:
with open(file_path, 'r') as file:
data = file.readlines()
return data
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
return None
def sort_data(data):
sorted_data = sorted(data)
return sorted_data
def write_data(file_path, data):
Output:
Story: