0% found this document useful (0 votes)
16 views35 pages

Tayyab

The document contains solutions to 14 questions on Artificial Intelligence concepts using Python. The questions cover topics like multiplication tables, prime number checking, factorials, lists, sets, calendars, matrices, search algorithms, simulated annealing and genetic algorithms. Detailed programs with outputs are provided as solutions for each question.

Uploaded by

MassabaliKhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views35 pages

Tayyab

The document contains solutions to 14 questions on Artificial Intelligence concepts using Python. The questions cover topics like multiplication tables, prime number checking, factorials, lists, sets, calendars, matrices, search algorithms, simulated annealing and genetic algorithms. Detailed programs with outputs are provided as solutions for each question.

Uploaded by

MassabaliKhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

UNIVERSITY OF AZAD JAMMU AND KASHMIR

BSCS | Bachelor of Computer Science & Information


Technology | 2019-2023
7th Semester

Artificial Intelligence
Lab Task

Submitted To: Dr.Wajid Arshad Abbasi

Submitted by: Tayyab Altaf Qureshi

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:

Q.02:- Write a python program to check whether the given number is


prime or not?
Answer:
Program:-
def is_prime(num):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
return False
return True
else:
return False

num = int(input("Enter a number: "))


if is_prime(num):
print(num, "is a prime number")
else:
print(num, "is not a prime number")

Output:

Q.03:- Write a python program to find factorial of the given number?


Answer:
Program:-
def factorial(num):
if num == 0:
return 1
else:
return num * factorial(num-1)

num = int(input("Enter a number: "))


print("The factorial of", num, "is", factorial(num))

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:

Q.05:- Write a python program to implement List methods (Add,


Append, Extend & Delete).
Answer:
Program:-
# Add elements
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1 += list2
print("Added list: ", list1)

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

Q.07:- Write a python program to generate Calendar for the given


month and year?
Answer:
Program:-
import calendar

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

Q.08:- Write a python program to implement Simple Calculator


program?
Answer:
Program:-
# Input two numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

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

Q.09:- Write a Python program to add two matrices?


Answer:-
Program:-
def add_matrices(matrix1, matrix2):
result = []
for i in range(len(matrix1)):
row = []
for j in range(len(matrix1[0])):
row.append(matrix1[i][j] + matrix2[i][j])
result.append(row)
return result

matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


matrix2 = [[10, 11, 12], [13, 14, 15], [16, 17, 18]]
result = add_matrices(matrix1, matrix2)

for row in result:


print(row)

Output:-

==================

Q.10:- Write a python program to Transpose a Matrix.


Answer:-

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

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

result = transpose_matrix(matrix)

for row in result:


print(row)
Output:-

=========================

Q.11.a):- Write a python program to remove punctuations from the


given string?
Answer:-

Program:-
import string

def remove_punctuation(input_string):
result = ""
for char in input_string:
if char not in string.punctuation:
result += char
return result

input_string = "Hello, World! How are you today?"

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

============================

Q.12.a):- Write a python program to implement Breadth First


Search Traversal?
Answer:-
Program:-
from collections import defaultdict

class Graph:
def __init__(self):
self.graph = defaultdict(list)

def addEdge(self, u, v):


self.graph[u].append(v)

def BFS(self, s):


visited = [False] * (max(self.graph) + 1)
queue = []
queue.append(s)
visited[s] = True

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)

print("Following is Breadth First Traversal (starting from vertex 2)")


g.BFS(2)
Output:-

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

def addEdge(self, u, v):


self.graph[u].append(v)

def DFSUtil(self, v, visited):


visited[v] = True
print(v, end = ' ')

for i in self.graph[v]:
if not visited[i]:
self.DFSUtil(i, visited)

def DFS(self, v):


visited = [False] * (max(self.graph) + 1)
self.DFSUtil(v, visited)
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 DFS from (starting from vertex 2)")


g.DFS(2)
Output:-

===============================

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 acceptance_probability(old_cost, new_cost, temperature):


return math.exp((old_cost - new_cost) / temperature)

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]

while temperature > 1e-10:


new_x = generate_neighbor(x)
new_cost = objective_function(new_x)

if acceptance_probability(cost, new_cost, temperature) > random.uniform(0,


1):
x = new_x
cost = new_cost

temperature *= cooling_rate
x_values.append(x[0])
y_values.append(x[1])
cost_values.append(cost)

plt.plot(x_values, y_values, 'o-')


plt.plot(x_values[-1], y_values[-1], 'ro')
plt.title("Simulated Annealing")
plt.xlabel("x")
plt.ylabel("y")
plt.show()

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

x = [random.uniform(-10, 10), random.uniform(-10, 10)]


simulated_annealing(x)
Output:-
The output will be two plots. One showing the path taken by the
simulated annealing algorithm and another showing the objective
function value at each iteration.
Here's an example output:

Simulated Annealing plot:

![Simulated_Annealing_Plot](https://i.imgur.com/LhWlITm.png)

Objective Function plot:

![Objective_Function_Plot](https://i.imgur.com/0YAEvJb.png)

And the final optimized solution and its corresponding cost value will
be returned:

[-0.1160803557890187, 1.3846988016892398], -1.8770254433954627


=========================
Q.14:- Solve the Knapsack problem using Genetic Algorithms using
Python.

Answer:-
Program:-
import random
import numpy as np

def knapsack_fitness(population, weights, values, capacity):


fitness = np.zeros(population.shape[0])
for i in range(population.shape[0]):
total_weight = np.sum(population[i] * weights)
if total_weight > capacity:
fitness[i] = 0
else:
fitness[i] = np.sum(population[i] * values)
return fitness

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

def single_point_crossover(parent1, parent2):


crossover_point = random.randint(0, len(parent1) - 1)
child1 = np.concatenate((parent1[0:crossover_point],
parent2[crossover_point:]))
child2 = np.concatenate((parent2[0:crossover_point],
parent1[crossover_point:]))
return child1, child2
def mutation(child, mutation_probability):
for i in range(len(child)):
random_value = random.uniform(0, 1)
if random_value < mutation_probability:
child[i] = 1 - child[i]
return child

def genetic_algorithm(weights, values, capacity, population_size,


num_generations, mutation_probability):
population = np.random.randint(2, size=(population_size, len(weights)))
for i in range(num_generations):
fitness = knapsack_fitness(population, weights, values, capacity)
new_population = []
for j in range(population_size):
parent1 = population[roulette_wheel_selection(fitness)]
parent2 = population[roulette_wheel_selection(fitness)]
child1, child2 = single_point_crossover(parent1, parent2)
child1 = mutation(child1, mutation_probability)
child2 = mutation(child2, mutation_probability)
new_population.append(child1)
new_population.append(child2)
population = np.array(new_population[0:population_size])
fitness = knapsack_fitness(population, weights, values, capacity)
best_index = np.argmax(fitness)
return population[best_index], fitness[best_index]
weights = [10, 20, 30]
values = [60, 100, 120]
capacity = 50
population_size = 100
num_generations = 1000
mutation_probability = 0.01
best_solution, best_fitness = genetic_algorithm(weights, values, capacity,
population_size, num_generations, mutation_probability)

print("Best solution: ", best_solution)

print("Best fitness: ", best_fitness)

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.
=====================================

Q.15:- Write a program to implement Tic-Tac-Toe game using python.


Answer:-
Program:-
def print_board(board):
print(' | |')
print(' ' + board[0] + ' | ' + board[1] + ' | ' + board[2])
print(' | |')
print('---|---|---')
print(' | |')
print(' ' + board[3] + ' | ' + board[4] + ' | ' + board[5])
print(' | |')
print('---|---|---')
print(' | |')
print(' ' + board[6] + ' | ' + board[7] + ' | ' + board[8])
print(' | |')

def check_winner(board, player):


if (board[0] == player and board[1] == player and board[2] == player) or \
(board[3] == player and board[4] == player and board[5] == player) or \
(board[6] == player and board[7] == player and board[8] == player) or \
(board[0] == player and board[3] == player and board[6] == player) or \
(board[1] == player and board[4] == player and board[7] == player) or \
(board[2] == player and board[5] == player and board[8] == player) or \
(board[0] == player and board[4] == player and board[8] == player) or \
(board[2] == player and board[4] == player and board[6] == player):
return True
else:
return False

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!
>
======================================================

Q.16:- Implement Reinforcement Q-Learning from Scratch in Python


with OpenAI Gym
Answer:-
Program:-
import gym
import numpy as np

# Load the environment


env = gym.make('FrozenLake-v0')

# Set the parameters for the Q-table


state_space_size = env.observation_space.n
action_space_size = env.action_space.n

# Initialize the Q-table with all zeros


Q = np.zeros((state_space_space, action_space_size))

# Set the learning parameters


num_episodes = 10000
max_steps_per_episode = 100
learning_rate = 0.1
discount_rate = 0.99

# 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

for step in range(max_steps_per_episode):


# Choose an action (explore or exploit)
exploration_rate_threshold = np.random.uniform(0, 1)
if exploration_rate_threshold > exploration_rate:
action = np.argmax(Q[state, :])
else:
action = env.action_space.sample()

# Take the action and observe the new state and reward
new_state, reward, done, info = env.step(action)

# Update the Q-table


Q[state, action] = (1 - learning_rate) * Q[state, action] + \
learning_rate * (reward + discount_rate *
np.max(Q[new_state, :]))

state = new_state
rewards_current_episode += reward

if done:
break

# Decay the exploration rate


exploration_rate = min_exploration_rate + \
(max_exploration_rate - min_exploration_rate) * np.exp(-
exploration_decay_rate * episode)

rewards_all_episodes.append(rewards_current_episode)

# Print the Q-table


print("Q-table:")
print(Q)

# Print the rewards over all episodes


print("Rewards over all episodes:")
print(rewards_all_episodes)

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]]

Rewards over all episodes:


[0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0,
1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0,
0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0,
1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0,
0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0
================================

You might also like