Tayyab
Tayyab
Artificial Intelligence
Lab Task
Q.01:- Write a python program to print the multiplication table for the
given number?
Answer:
Program:-
def print_multiplication_table(n):
for i in range(1, 11):
print(n, 'x', i, '=', n*i)
num = int(input("Enter a number: "))
print_multiplication_table(num)
Output:
Output:
Output:
Q.04:- Write a python program to implement List operations (Nested
List, Length, Concatenation, Membership, Iteration, Indexing and
Slicing)?
Answer:
Program:-
# Nested List
nested_list = [[1, 2, 3], [4, 5, 6]]
print("Nested List: ", nested_list)
# Length
list1 = [1, 2, 3, 4, 5]
print("Length of list1: ", len(list1))
# Concatenation
list2 = [6, 7, 8, 9]
list3 = list1 + list2
print("Concatenated list: ", list3)
# Membership
print("Is 3 in list1?", 3 in list1)
# Iteration
print("Elements in list1:")
for item in list1:
print(item)
# Indexing
print("First element in list1: ", list1[0])
# Slicing
print("Sliced list: ", list1[1:3])
Output:
# Append elements
list1 = [1, 2, 3]
list1.append(4)
print("Appended list: ", list1)
# Extend elements
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print("Extended list: ", list1)
# Delete elements
list1 = [1, 2, 3, 4, 5, 6]
del list1[2]
print("Deleted list: ", list1)
Output:
Q.06:- Write a python program to Illustrate Different Set Operations?
Answer:
Program:-
# Initial Sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print("Set1:", set1)
print("Set2:", set2)
# Union
set_union = set1 | set2
print("Union:", set_union)
# Intersection
set_intersection = set1 & set2
print("Intersection:", set_intersection)
# Difference
set_difference = set1 - set2
print("Difference (Set1 - Set2):", set_difference)
# Symmetric Difference
set_symmetric_difference = set1 ^ set2
print("Symmetric Difference:", set_symmetric_difference)
# Subset
print("Is Set1 a Subset of Set2:", set1.issubset(set2))
# Superset
print("Is Set1 a Superset of Set2:", set1.issuperset(set2))
Output:
# Input
year = int(input("Enter year: "))
month = int(input("Enter month: "))
# Generate Calendar
cal = calendar.monthcalendar(year, month)
print("Calendar:")
print("Mo Tu We Th Fr Sa Su")
for week in cal:
for day in week:
if day == 0:
print(" ", end=" ")
else:
print("%2d" % day, end=" ")
print()
Output:
# Input operator
op = input("Enter operator (+, -, *, /): ")
# Perform calculation
if op == "+":
result = num1 + num2
op_symbol = "+"
elif op == "-":
result = num1 - num2
op_symbol = "-"
elif op == "*":
result = num1 * num2
op_symbol = "*"
elif op == "/":
result = num1 / num2
op_symbol = "/"
else:
print("Invalid operator")
result = None
# Output result
if result is not None:
print(f"{num1} {op_symbol} {num2} = {result}")
Output:
Output:-
==================
Program:-
def transpose_matrix(matrix):
result = []
for i in range(len(matrix[0])):
row = []
for j in range(len(matrix)):
row.append(matrix[j][i])
result.append(row)
return result
result = transpose_matrix(matrix)
=========================
Program:-
import string
def remove_punctuation(input_string):
result = ""
for char in input_string:
if char not in string.punctuation:
result += char
return result
result = remove_punctuation(input_string)
print(result)
Output:-
==========================
Q.11.b):- Write a python program to sort the sentence in
alphabetical order?
Answer:-
Program:-
def sort_sentence(sentence):
words = sentence.split()
words.sort()
return " ".join(words)
sentence = "the quick brown fox jumps over the lazy dog"
result = sort_sentence(sentence)
print(result)
Output:-
============================
class Graph:
def __init__(self):
self.graph = defaultdict(list)
while queue:
s = queue.pop(0)
print(s, end = " ")
for i in self.graph[s]:
if not visited[i]:
queue.append(i)
visited[i] = True
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)
======================
Q.12.b):- Write a python program to implement Depth First Search
Traversal?
Answer:
Program:-
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
for i in self.graph[v]:
if not visited[i]:
self.DFSUtil(i, visited)
===============================
Q.13:- Implement Simulated annealing in python and creates a line plot of the
objective function and clearly marks the function optima.
Answer:-
Program:-
import random
import math
import matplotlib.pyplot as plt
def objective_function(x):
return -(math.sin(x[0]) + math.cos(x[1]))
def generate_neighbor(x):
return [x[0] + random.uniform(-0.1, 0.1), x[1] + random.uniform(-0.1, 0.1)]
def simulated_annealing(x):
temperature = 1000
cooling_rate = 0.95
cost = objective_function(x)
x_values = [x[0]]
y_values = [x[1]]
cost_values = [cost]
temperature *= cooling_rate
x_values.append(x[0])
y_values.append(x[1])
cost_values.append(cost)
plt.plot(cost_values)
plt.plot(len(cost_values) - 1, cost_values[-1], 'ro')
plt.title("Objective Function")
plt.xlabel("Iteration")
plt.ylabel("Cost")
plt.show()
return x, cost


And the final optimized solution and its corresponding cost value will
be returned:
Answer:-
Program:-
import random
import numpy as np
def roulette_wheel_selection(fitness):
fitness_sum = np.sum(fitness)
probability = fitness / fitness_sum
probability_cumulative = np.cumsum(probability)
random_value = random.uniform(0, 1)
for i in range(fitness.shape[0]):
if random_value < probability_cumulative[i]:
return i
Output:-
The output of the 8th program is a graph showing the path of the simulated
annealing algorithm, and another graph showing the change in the objective
function during the algorithm's iterations. The program also returns the final
state and cost of the objective function.
=====================================
def main():
board = [' ' for x in range(9)]
player = 'X'
while True:
print_board(board)
print('Player ' + player + ' turn. Which space do you want to play? (0-8)')
move = int(input())
if board[move] == ' ':
board[move] = player
else:
print('That space is already taken.')
continue
if check_winner(board, player):
print_board(board)
print('Player ' + player + ' wins!')
break
if player == 'X':
player = 'O'
else:
player = 'X'
if __name__ == "__main__":
main()
Output:-
| |
| |
| |
---|---|---
| |
| |
| |
---|---|---
| |
| |
| |
Player X turn. Which space do you want to play? (0-8)
0
| |
X| |
| |
---|---|---
| |
| |
| |
---|---|---
| |
| |
| |
Player O turn. Which space do you want to play? (0-8)
2
| |
X| |O
| |
---|---|---
| |
| |
| |
---|---|---
| |
| |
| |
Player X turn. Which space do you want to play? (0-8)
6
| |
X| |O
| |
---|---|---
| |
| |
| |
---|---|---
| |
X| |
| |
Player O turn. Which space do you want to play? (0-8)
4
| |
X| |O
| |
---|---|---
| |
|O|
| |
---|---|---
| |
X| |
| |
Player X turn. Which space do you want to play? (0-8)
8
| |
X| |O
| |
---|---|---
| |
|O|
| |
---|---|---
| |
X| |X
| |
Player O turn. Which space do you want to play? (0-8)
3
| |
X| |O
| |
---|---|---
| |
O|O|
| |
---|---|---
| |
X| |X
| |
Player X turn. Which space do you want to play? (0-8)
7
| |
X| |O
| |
---|---|---
| |
O|O|
| |
---|---|---
| |
X|X|X
| |
Player X wins!
>
======================================================
# Exploration-exploitation trade-off
exploration_rate = 0.1
max_exploration_rate = 1.0
min_exploration_rate = 0.01
exploration_decay_rate = 0.001
# Train the Q-table through reinforcement learning
rewards_all_episodes = []
for episode in range(num_episodes):
state = env.reset()
done = False
rewards_current_episode = 0
# Take the action and observe the new state and reward
new_state, reward, done, info = env.step(action)
state = new_state
rewards_current_episode += reward
if done:
break
rewards_all_episodes.append(rewards_current_episode)
Output:-
Q-table:
[[1.45035497e-01 9.67767907e-02 9.59258395e-02 9.78485823e-02]
[3.86274716e-04 8.90734070e-04 8.66770388e-03 2.46198197e-01]
[1.55299384e-01 2.45811387e-01 2.46070509e-01 1.55940224e-01]
[9.25660115e-02 1.05243713e-01 8.06546851e-02 1.06389382e-01]
[1.44868345e-01 2.45382373e-01 4.07892794e-01 1.50818296e-01]
[0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00]
[3.05444346e-02 8.52302869e-02 9.85487914e-01 7.88980889e-02]
[0.00000000e+00 0.00000000e+00 0.00000000e+00
0.00000000e+00]]