0% found this document useful (0 votes)
40 views

Ai Lab 01

Uploaded by

doodhjaleybi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Ai Lab 01

Uploaded by

doodhjaleybi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Bahria University

Karachi Campus

COURSE:
Artificial Intelligence Lab
TERM: SPRING 2024, CLASS: BSE- 6(A)

Submitted By:
EIMA NASIR 79297
(Name) (Registration. No.)

Submitted To:

Engr. Hamza/Engr. Faiz ul Haque Zeya

Signed Remarks: Score:_____

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 01]


INDEX
SNO DATE LAB LAB OBJECTIVE SIGN
NO

01 18/02/24 01 python programming


with python Interview questions

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 01]


Bahria University
Karachi Campus

LAB EXPERIMENT NO.


_1_
LIST OF TASKS
TASK NO OBJECTIVE
1 Create a simple calculator program that can perform basic arithmetic
operations like addition, subtraction, multiplication, and division.
2 Write a program that generates a random number and asks the user to guess
it. Provide hints such as "too high" or "too low" until the user guesses the
correct number.
3 Write a program that checks if a given string is a palindrome (reads the same
forwards and backwards).
4 Create a program that counts the frequency of words in a given text file or
input string.
5 Write a program that prints the numbers from 1 to 100. But for multiples of
three, print "Fizz" instead of the number, and for the multiples of five, print
"Buzz". For numbers that are multiples of both three and five, print "Fizz
Buzz".
6 Create a program that converts temperatures between Celsius and
Fahrenheit.
7 Implement the classic game of Hangman where the user has to guess a word
by suggesting letters within a certain number of attempts.
8 Write a program that reads data from a text file, performs some operation
(e.g., sorting, filtering), and writes the result to another file.

Submitted On:
[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 01]
Date: 18/02/2024

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 01]


Task No. 01: Create a simple calculator program that can perform basic
arithmetic operations like addition, subtraction, multiplication, and division.

Solution:

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 01]


[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 01]
Task No. 02: Write a program that generates a random number and asks the
user to guess it. Provide hints such as "too high" or "too low" until the user
guesses the correct number.

Solution:

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 01]


Task No. 03: Write a program that checks if a given string is a palindrome
(reads the same forwards and backwards).

Solution:

Task No. 04: Create a program that counts the frequency of words in a given
text file or input string.

Solution for text file:


def count_word_frequency(text):
word_freq = {}
words = text.split()
for word in words:
# Remove punctuation marks
word = word.strip('.,!?;:"()[]{}')
# Convert to lowercase
word = word.lower()
if word:
word_freq[word] = word_freq.get(word, 0) + 1
return word_freq
def main():
# Read the text from the file
file_path = 'story.txt'
try:

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 01]


with open(file_path, 'r') as file:
text = file.read()
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
return
# Count word frequency
word_freq = count_word_frequency(text)
# Display results
print("Word frequency in the text:")
for word, freq in word_freq.items():
print(f"{word}: {freq}")
if __name__ == "__main__":
main()

Output:

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 01]


Solution for input string:
def count_word_frequency(text):
word_freq = {}
words = text.split()
for word in words:
# Remove punctuation marks
word = word.strip('.,!?;:"()[]{}')
# Convert to lowercase
word = word.lower()
if word:
word_freq[word] = word_freq.get(word, 0) + 1
return word_freq
def main():
# Input text from the user
text = input("Enter the text: ")
# Count word frequency
word_freq = count_word_frequency(text)
# Display results
print("Word frequency in the text:")
for word, freq in word_freq.items():
print(f"{word}: {freq}")
if __name__ == "__main__":
main()

Output:

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 01]


Task No. 05: Write a program that prints the numbers from 1 to 100. But for
multiples of three, print "Fizz" instead of the number, and for the multiples of
five, print "Buzz". For numbers that are multiples of both three and five,
print "Fizz Buzz".

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:

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 01]


Task No. 06: Create a program that converts temperatures between Celsius
and Fahrenheit.

Solution:

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 01]


Task No. 07: Implement the classic game of Hangman where the user has to
guess a word by suggesting letters within a certain number of attempts.

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

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 01]


Output:

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

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 01]


try:
with open(file_path, 'w') as file:
for line in data:
file.write(line)
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
def main():
input_file = 'story.txt'
output_file = 'sorted_story.txt'
# Read data from input file
data = read_data(input_file)
if data is None:
return
# Sort the data
sorted_data = sort_data(data)
# Write sorted data to output file
write_data(output_file, sorted_data)
print(f"Data from '{input_file}' has been sorted and written to '{output_file}'.")
if __name__ == "__main__":
main()

Output:

Story:

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 01]


Sorted Story:

[EIMA NASIR (02-131212-020)] [ARTIFICIAL INTELLIGENCE LAB 01]

You might also like