AI Lab
AI Lab
Sandeep Raj
Roll No: 2101043CS (Assistant Professor)
Branch: CSE
SUSHANT KUMAR 2101043CS CSE
INDEX
2|Pag e
SUSHANT KUMAR 2101043CS CSE
Assignment 1
1. Write a python program to display a particular month of a year using calendar.
import calendar
def display_month(year, month):
print(calendar.month(year, month))
display_month(2023, 11)
def print_all_months(year):
for month in range(1, 13):
print(calendar.month_name[month], year)
print_all_months(2023)
3. Write a python program to print date, time for today and now.
3|Pag e
SUSHANT KUMAR 2101043CS CSE
import datetime
def print_date_time():
today = datetime.date.today()
print("Today's Date:", today)
now = datetime.datetime.now()
print("Current Date and Time:", now)
print_date_time()
4. Write a python program to add some days to your present date and
print the date added.
def add_days_to_date(days_to_add):
today = datetime.date.today()
future_date = today + datetime.timedelta(days=days_to_add)
print(f"Today's Date: {today}")
print(f"Date after adding {days_to_add} days: {future_date}")
days_to_add = 10
add_days_to_date(days_to_add)
4|Pag e
SUSHANT KUMAR 2101043CS CSE
Assignment 2
1. Write a python program to display a particular month of a year using calendar module.
import calendar
year = 2023
month = 10
print(calendar.month(year, month))
import calendar
year = 2023
for month in range(1, 13):
print(calendar.month_name[month])
if number > 0:
print("Number is positive")
elif number == 0:
print("Number is zero")
else:
print("Number is negative")
5. Write a python program to read a number and display corresponding day using if-else.
if number == 1:
print("Monday")
elif number == 2:
print("Tuesday")
elif number == 3:
print("Wednesday")
elif number == 4:
6|Pag e
SUSHANT KUMAR 2101043CS CSE
print("Thursday")
elif number == 5:
print("Friday")
elif number == 6:
print("Saturday")
elif number == 7:
print("Sunday")
else:
print("Invalid input. Enter a number between 1 and 7.")
6. Write a python program to check whether the given string is palindrome or not.
def is_palindrome(s):
s = s.lower().replace(" ", "")
return s == s[::-1]
string = input("Enter a string: ")
if is_palindrome(string):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
num = int(input("Enter a number to find its factorial: "))
print("Factorial of", num, "is", factorial(num))
7|Pag e
SUSHANT KUMAR 2101043CS CSE
8. Write a python function that takes two lists and returns True if they are equal
otherwise false.
list_a = [1, 2, 3, 4, 5]
list_b = [1, 2, 3, 4, 5]
list_c = [1, 2, 3, 4, 6]
print("Are list_a and list_b equal?", check_equality(list_a, list_b))
print("Are list_a and list_c equal?", check_equality(list_a, list_c))
8|Pag e
SUSHANT KUMAR 2101043CS CSE
Assignment 3
1. We have two functions named numpy.empty() and numpy. full() to create an empty
and full array.
(a) We create an empty array of 3X4 and a full array of 3X3 of INTEGER type.
import numpy as np
empty_array_int = np.empty((3, 4), dtype=int)
full_array_int = np.full((3, 3), 7, dtype=int)
print("Empty array of 3x4 (integer):")
print(empty_array_int)
print("Full array of 3x3 with value 7 (integer):")
print(full_array_int)
(b) We create an empty array of 4X2 and a full array of 4X3 of INTEGER and
FLOAT type.
empty_array_int_float = np.empty((4, 2), dtype=int)
full_array_int_float = np.full((4, 3), 5.5, dtype=float)
print("Empty array of 4x2 (integer):")
print(empty_array_int_float)
print("Full array of 4x3 with value 5.5 (float):")
print(full_array_int_float)
9|Pag e
SUSHANT KUMAR 2101043CS CSE
(c) We create an empty array of 3X3 and a full array of 5X3 of FLOAT type.
zeroes_1d = np.zeros(5)
print("One-dimensional array of zeros:")
print(zeroes_1d)
shape = (2, 3, 4)
zeroes_md = np.zeros(shape)
print("Multi-dimensional array of zeros:")
print(zeroes_md)
tuple_shape = (2, 3)
zeroes_tuple = np.zeros(tuple_shape)
print("Zeros array with tuple data type:")
print(zeroes_tuple)
11 | P a g e
SUSHANT KUMAR 2101043CS CSE
specified_values = [2, 6]
result = np.isin(arr, specified_values)
print("Specified values present in array:", result)
def fibonacci_binet(n):
sqrt_5 = np.sqrt(5)
phi = (1 + sqrt_5) / 2
fib = np.rint(((phi ** np.arange(1, n+1)) - ((-1/phi) ** np.arange(1, n+1))) / sqrt_5)
return fib.astype(int)
first_five_fib = fibonacci_binet(5)
print("First 5 Fibonacci numbers using Binet's formula:", first_five_fib)
n = 10
first_n_fib = fibonacci_binet(n)
print(f"First {n} Fibonacci numbers using Binet's formula:", first_n_fib)
5. How to get all 2D diagonals of a 3D NumPy array.So, for this we are using
numpy.diagonal() function of NumPy library. This function return specified diagonals
from an n-dimensional array.
12 | P a g e
SUSHANT KUMAR 2101043CS CSE
13 | P a g e
SUSHANT KUMAR 2101043CS CSE
Assignment 4
1. (a) Write a Pandas program to create a subset of a given series based on value and
condition.
s = pd.Series([0,1,2,3,4,5,6,7,8,9,10])
print("Original Data Series:")
print(s)
print("\nSubset of the above Data Series:")
n=6
new_s = s[s < n]
print(new_s)
(b) Write a Pandas program to create the mean and standard deviation of the
data of a given Series.
s = pd.Series(data = [1,2,3,4,5,6,7,8,9,5,3])
print("Original Data Series:")
print(s)
print("Mean of the said Data Series:")
print(s.mean())
print("Standard deviation of the said Data Series:")
print(s.std())
14 | P a g e
SUSHANT KUMAR 2101043CS CSE
(c) Write a Pandas program to get the items of a given series not present in
another given series.
15 | P a g e
SUSHANT KUMAR 2101043CS CSE
(d) Write a Pandas program to get the items which are not common of two given
series.
(e) Write a Pandas program to compute the minimum, 25th percentile, median,
75th, and maximum of a given series.
num_state = np.random.RandomState(100)
num_series = pd.Series(num_state.normal(10, 4, 20))
print("Original Series:")
print(num_series)
result = np.percentile(num_series, q=[0, 25, 50, 75, 100])
print("\nMinimum, 25th percentile, median, 75th, and maximum of a given series:")
print(result)
16 | P a g e
SUSHANT KUMAR 2101043CS CSE
2. (a) Write a Pandas program to calculate the frequency counts of each unique
value of a given series.
17 | P a g e
SUSHANT KUMAR 2101043CS CSE
(b) Write a Pandas program to display most frequent value in a given series and
replace everything else as 'Other' in the series.
(c) Write a Pandas program to find the positions of numbers that are multiples of 5 of
a given series.
18 | P a g e
SUSHANT KUMAR 2101043CS CSE
3. (a) Write a Pandas program convert the first and last character of each word to upper
case in each word of a given series.
19 | P a g e
SUSHANT KUMAR 2101043CS CSE
(c) Write a Pandas program to get the day of month, day of year, week number and
day of week from a given series of date strings.
20 | P a g e
SUSHANT KUMAR 2101043CS CSE
Assignment 5
1. Write a Pandas program to create and display a Data Frame from a specified
dictionary data which has the index labels.
import pandas as pd
import numpy as np
df = pd.DataFrame(exam_data , index=labels)
print(df)
import pandas as pd
import numpy as np
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
21 | P a g e
SUSHANT KUMAR 2101043CS CSE
df = pd.DataFrame(exam_data , index=labels)
print(df.info())
3. Write a Pandas program to select the 'name' and 'score' columns from the following
Data Frame.
df = pd.DataFrame(exam_data , index=labels)
print("Select specific columns:")
print(df[['name', 'score']])
22 | P a g e
SUSHANT KUMAR 2101043CS CSE
4. Write a Pandas program to select the specified columns and rows from a given data
frame select 'name' and 'score' columns in rows 1, 3, 5, 6 from the following data
frame.
df = pd.DataFrame(exam_data , index=labels)
print("Select specific columns and rows:")
print(df.iloc[[1, 3, 5, 6], [1, 3]])
5. Write a Pandas program to select the rows the score is between 15 and 20
(inclusive).
df = pd.DataFrame(exam_data , index=labels)
print("Rows where score between 15 and 20 (inclusive):")
print(df[df['score'].between(15, 20)])
23 | P a g e
SUSHANT KUMAR 2101043CS CSE
6. Write a Pandas program to change the score in row 'd' to 11.5.
df = pd.DataFrame(exam_data , index=labels)
print("\nOriginal data frame:")
print(df)
print("\nChange the score in row 'd' to 11.5:")
df.loc['d', 'score'] = 11.5
print(df)
7. Write a Pandas program to calculate the sum of the examination attempts by the
students.
24 | P a g e
SUSHANT KUMAR 2101043CS CSE
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael',
'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print("\nSum of the examination attempts by the students:")
print(df['attempts'].sum())
df = pd.DataFrame(exam_data , index=labels)
print("\nMean score for each different student in data frame:")
print(df['score'].mean())
25 | P a g e
SUSHANT KUMAR 2101043CS CSE
Assignment 6
while queue:
state, path = queue.popleft()
26 | P a g e
SUSHANT KUMAR 2101043CS CSE
if state == goal_state:
return path
visited.add(tuple(state))
for move_option in possible_moves(state):
new_state = move(state, move_option)
if tuple(new_state) not in visited:
queue.append((new_state, path + [move_option]))
return None
start = [1, 2, 3, 0, 4, 5, 6, 7, 8]
goal = [0, 1, 2, 3, 4, 5, 6, 7, 8]
solution = bfs_8_puzzle(start, goal)
if solution:
print("Solution found:", solution)
else:
print("No solution exists.")
N=8
def is_safe(board, row, col):
for i in range(col):
if board[row][i]:
return False
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j]:
return False
for i, j in zip(range(row, N, 1), range(col, -1, -1)):
if board[i][j]:
return False
return True
def print_solution(board):
for i in range(N):
for j in range(N):
print(board[i][j], end=" ")
print()
while queue:
s = queue.pop(0)
print(s, end=" ")
28 | P a g e
SUSHANT KUMAR 2101043CS CSE
for i in self.graph[s]:
if not visited[i]:
queue.append(i)
visited[i] = True
for i in self.graph[v]:
if not visited[i]:
self.dfs_util(i, visited)
g = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.add_edge(3, 3)
print("BFS:")
g.bfs(2)
print("\nDFS:")
g.dfs(2)
29 | P a g e
SUSHANT KUMAR 2101043CS CSE
print(f"Move disk 1 from {source} to {target}")
return
tower_of_hanoi(n - 1, source, target, auxiliary)
print(f"Move disk {n} from {source} to {target}")
tower_of_hanoi(n - 1, auxiliary, source, target)
n_disks = 3
tower_of_hanoi(n_disks, 'A', 'B', 'C')
30 | P a g e
SUSHANT KUMAR 2101043CS CSE
Assignment 7
if current_node.state == goal_state:
path = []
while current_node.parent:
path.append((current_node.state, current_node.action))
current_node = current_node.parent
path.append((initial_state, None))
return list(reversed(path))
closed_set.add(current_node.state)
31 | P a g e
SUSHANT KUMAR 2101043CS CSE
new_node = Node(new_state, current_node, action, new_cost,
heuristic(new_state, goal_state))
def possible_actions(state):
return [(1, 0), (0, 1)]
def action_cost(action):
return 1
initial_state = (0, 0)
goal_state = (4, 5)
solution = astar_search(initial_state, goal_state)
if solution:
print("Solution found:")
for step in solution:
print(step)
else:
print("No solution exists.")
AND_nodes = condition['AND']
Path_A = ' AND '.join(AND_nodes)
PathA = sum(H[node]+weight for node in AND_nodes)
32 | P a g e
SUSHANT KUMAR 2101043CS CSE
cost[Path_A] = PathA
if 'OR' in condition:
OR_nodes = condition['OR']
Path_B =' OR '.join(OR_nodes)
PathB = min(H[node]+weight for node in OR_nodes)
cost[Path_B] = PathB
return cost
Next = key[Index].split()
if len(Next) == 1:
Start =Next[0]
Path += '<--' +shortest_path(Start, Updated_cost, H)
else:
Path +='<--('+key[Index]+') '
Start = Next[0]
Path += '[' +shortest_path(Start, Updated_cost, H) + ' + '
Start = Next[-1]
Path += shortest_path(Start, Updated_cost, H) + ']'
return Path
H = {'A': -1, 'B': 5, 'C': 2, 'D': 4, 'E': 7, 'F': 9, 'G': 3, 'H': 0, 'I':0, 'J':0}
Conditions = {
33 | P a g e
SUSHANT KUMAR 2101043CS CSE
'A': {'OR': ['B'], 'AND': ['C', 'D']},
'B': {'OR': ['E', 'F']},
'C': {'OR': ['G'], 'AND': ['H', 'I']},
'D': {'OR': ['J']}
}
weight = 1
print('Updated Cost :')
Updated_cost = update_cost(H, Conditions, weight=1)
print('*'*75)
print('Shortest Path :\n',shortest_path('A', Updated_cost,H))
import random
def evaluate_function(x):
return -1 * (x ** 2)
def get_neighbors(current_solution):
return [current_solution + random.uniform(-0.5, 0.5)]
return current
initial_solution = 2
maximum_solution = hill_climbing(initial_solution, 100, get_neighbors,
evaluate_function)
print("Maximum found:", maximum_solution)
34 | P a g e
SUSHANT KUMAR 2101043CS CSE
import math
def evaluate(state):
return state
def possible_moves(state):
return [state - 1, state + 1]
if maximizing_player:
max_eval = -math.inf
for move in possible_moves(state):
eval = minimax(move, depth - 1, False)
max_eval = max(max_eval, eval)
return max_eval
else:
min_eval = math.inf
for move in possible_moves(state):
eval = minimax(move, depth - 1, True)
min_eval = min(min_eval, eval)
return min_eval
if maximizing_player:
max_eval = -math.inf
for move in possible_moves(state):
eval = alpha_beta(move, depth - 1, alpha, beta, False)
max_eval = max(max_eval, eval)
initial_state = 10
depth = 4
36 | P a g e
SUSHANT KUMAR 2101043CS CSE
Assignment 8
jug1_capacity = 4
jug2_capacity = 3
target_amount = 2
solution = water_jug(jug1_capacity, jug2_capacity, target_amount)
print("Steps to reach the target:", solution)
import itertools
import random
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
deck = list(itertools.product(ranks, suits))
random.shuffle(deck)
print("Shuffled deck:")
37 | P a g e
SUSHANT KUMAR 2101043CS CSE
for card in deck:
print(f"{card[0]} of {card[1]}")
def max_bananas(matrix):
rows = len(matrix)
cols = len(matrix[0])
dp = [[0 for _ in range(cols)] for _ in range(rows)]
for i in range(rows - 1, -1, -1):
for j in range(cols - 1, -1, -1):
if i == rows - 1 and j == cols - 1:
dp[i][j] = matrix[i][j]
elif i == rows - 1:
dp[i][j] = matrix[i][j] + dp[i][j + 1]
elif j == cols - 1:
dp[i][j] = matrix[i][j] + dp[i + 1][j]
else:
dp[i][j] = matrix[i][j] + max(dp[i][j + 1], dp[i + 1][j])
return dp[0][0]
38 | P a g e
SUSHANT KUMAR 2101043CS CSE
import itertools
def traveling_salesman(graph):
cities = list(range(len(graph)))
min_path = None
min_cost = float('inf')
graph = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
shortest_path, min_distance = traveling_salesman(graph)
print("Shortest Path:", shortest_path)
print("Minimum Distance:", min_distance)
39 | P a g e
SUSHANT KUMAR 2101043CS CSE
Assignment 9
1.Commutative Law:
Write a Python function to demonstrate the commutative law for addition and
multiplication using user input.
def commutative_law():
a = float(input("Enter a number (a): "))
b = float(input("Enter another number (b): "))
sum_ab = a + b
sum_ba = b + a
print(f"Addition Commutative Law: a + b = {sum_ab} and b + a = {sum_ba}
(Equal: {sum_ab == sum_ba})")
prod_ab = a * b
prod_ba = b * a
print(f"Multiplication Commutative Law: a * b = {prod_ab} and b * a = {prod_ba}
(Equal: {prod_ab == prod_ba})")
commutative_law()
2.Associative Law:
Create a Python program that verifies the associative law for addition and
multiplication with a list of numbers.
def associative_law(numbers):
add_law_1 = sum(numbers)
add_law_2 = sum(numbers[0:len(numbers) // 2]) + sum(numbers[len(numbers) //
2:])
print(f"Addition Associative Law: (a + b) + c = {add_law_1} and a + (b + c) =
{add_law_2} (Equal: {add_law_1 == add_law_2})")
mul_law_1 = 1
40 | P a g e
SUSHANT KUMAR 2101043CS CSE
numbers = [2, 3, 4, 5, 6]
associative_law(numbers)
bool_a = True
bool_b = False
demorgans_laws(bool_a, bool_b)
def excluded_middle(proposition):
if proposition == True or proposition == False:
print(f"The proposition is either true or false: {proposition}")
else:
print("The proposition is not a simple true/false statement.")
excluded_middle(True)
excluded_middle(5 < 3)
42 | P a g e
SUSHANT KUMAR 2101043CS CSE
Assignment 10
1.Adsorption:
Develop a Python script to model adsorption using a simple adsorption isotherm
equation, allowing users to input values and plot the adsorption curve.
plt.plot(concentrations, adsorption)
plt.xlabel('Concentration')
plt.ylabel('Adsorption')
plt.title('Adsorption Isotherm Curve')
plt.show()
43 | P a g e
SUSHANT KUMAR 2101043CS CSE
2.Double Negation:
Write a Python function to apply double negation to a logical expression represented
as a string and return the simplified expression.
def double_negation(expression):
return f"Not (Not {expression})"
3.Law of Contradiction:
Create a Python program that checks if a given logical expression violates the law of
contradiction and provides feedback on the contradiction if found.
def contradiction_checker(expression):
negation = f"Not {expression}"
contradiction = expression and negation
if contradiction:
print(f"The expression {expression} violates the law of contradiction.")
else:
print(f"The expression {expression} does not violate the law of contradiction.")
logical_expression = True
contradiction_checker(logical_expression)
4.Modus Ponens:
Implement a Python function that represents a Modus Ponens inference rule. Given a
knowledge base with facts and an implication, the function should determine if the
conclusion can be derived.
44 | P a g e
SUSHANT KUMAR 2101043CS CSE
facts = [True]
implication_rule = (True, [True, "Then something happens"])
result = modus_ponens(facts, implication_rule)
print("Can the conclusion be derived? ", result)
5.Modus Tollens:
Create a Python program that demonstrates Modus Tollens. Given a conditional
statement and the negation of the consequent, the program should check if it implies
the negation of the antecedent.
conditional = ("If it rains, the ground gets wet", "The ground is not wet")
result = modus_tollens(conditional, "The ground gets wet")
print("Result:", result)
45 | P a g e
SUSHANT KUMAR 2101043CS CSE
Assignment 11
Quantifiers:
2. Write a Python program that checks if a given predicate logic statement with
universal quantifiers is true for a given domain.
def Q(y):
46 | P a g e
SUSHANT KUMAR 2101043CS CSE
return y % 2 == 0
3.Create a Python script that determines if a predicate logic statement with existential
quantifiers is satisfied in a set of data.
def P(x):
return x > 0
def Q(y):
return y % 2 == 0
47 | P a g e
SUSHANT KUMAR 2101043CS CSE
48 | P a g e