0% found this document useful (0 votes)
9 views48 pages

AI Lab

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

AI Lab

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

Submitted By: SUSHANT KUMAR Submitted To: Dr.

Sandeep Raj
Roll No: 2101043CS (Assistant Professor)
Branch: CSE
SUSHANT KUMAR 2101043CS CSE

INDEX

Serial No Assignment Date Page No


1. Assignment 1 24/08/2023 3-4

2. Assignment 2 31/08/2023 5-8

3. Assignment 3 07/09/2023 9-13

4. Assignment 4 14/09/2023 14-20

5. Assignment 5 21/09/2023 21-25

6. Assignment 6 12/10/2023 26-30

7. Assignment 7 19/10/2023 31-36

8. Assignment 8 26/10/2023 37-39

9. Assignment 9 02/11/2023 40-42

10. Assignment 10 03/11/2023 43-45

11. Assignment 11 09/11/2023 46-48

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)

2. Write a python program to print all the months of given year.

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

2. Write a python program to print all the months of given year.

import calendar
year = 2023
for month in range(1, 13):
print(calendar.month_name[month])

3. Write a python program to print a number is positive/negative using if-else.


5|Pag e
SUSHANT KUMAR 2101043CS CSE

number = float(input("Enter a number: "))

if number > 0:
print("Number is positive")
elif number == 0:
print("Number is zero")
else:
print("Number is negative")

4. Write a python program to find largest number among three numbers.

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

largest = max(num1, num2, num3)


print("The largest number is:", largest)

5. Write a python program to read a number and display corresponding day using if-else.

number = int(input("Enter a number (1-7): "))

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.")

7. Write a python program to find factorial of a given number using functions.

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.

def check_equality(list1, list2):


return list1 == list2

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.

empty_array_float = np.empty((3, 3), dtype=float)


full_array_float = np.full((5, 3), 3.14, dtype=float)
print("Empty array of 3x3 (float):")
print(empty_array_float)
print("Full array of 5x3 with value 3.14 (float):")
print(full_array_float)

2. (a) Creating a one-dimensional array with zeros using numpy.zeros().

zeroes_1d = np.zeros(5)
print("One-dimensional array of zeros:")
print(zeroes_1d)

(b)Creating a 2-dimensional array with zeros using numpy.zeros()


zeroes_2d = np.zeros((3, 4))
print("Two-dimensional array of zeros:")
print(zeroes_2d)

(c)Creating a Multi-dimensional array with zeros using numpy.zeros().


10 | P a g e
SUSHANT KUMAR 2101043CS CSE

shape = (2, 3, 4)
zeroes_md = np.zeros(shape)
print("Multi-dimensional array of zeros:")
print(zeroes_md)

(d)NumPy zeros array with an integer data type.

zeroes_int = np.zeros((2, 2), dtype=int)


print("Zeros array with integer data type:")
print(zeroes_int)

(e)NumPy Array with Tuple Data Type and Zeroes.

tuple_shape = (2, 3)
zeroes_tuple = np.zeros(tuple_shape)
print("Zeros array with tuple data type:")
print(zeroes_tuple)

3. How to check whether specified values are present in NumPy array.

11 | P a g e
SUSHANT KUMAR 2101043CS CSE

arr = np.array([1, 2, 3, 4, 5])

specified_values = [2, 6]
result = np.isin(arr, specified_values)
print("Specified values present in array:", result)

4. NumPy – Fibonacci Series using Binet Formula.


(a)To find first 5 Fibonacci numbers.

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)

(b)To find first ‘n’ Fibonacci numbers.

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

arr_3d = np.array([[[1, 2, 3],


[4, 5, 6],
[7, 8, 9]],

[[10, 11, 12],


[13, 14, 15],
[16, 17, 18]]])

diagonals = [np.diagonal(subarray) for subarray in arr_3d]


print("All 2D diagonals of the 3D array:")
print(diagonals)

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.

sr1 = pd.Series([1, 2, 3, 4, 5])


sr2 = pd.Series([2, 4, 6, 8, 10])
print("Original Series:")
print("sr1:")
print(sr1)
print("sr2:")
print(sr2)
print("\nItems of sr1 not present in sr2:")
result = sr1[~sr1.isin(sr2)]
print(result)

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.

sr1 = pd.Series([1, 2, 3, 4, 5])


sr2 = pd.Series([2, 4, 6, 8, 10])
print("Original Series:")
print("sr1:")
print(sr1)
print("sr2:")
print(sr2)
print("\nItems of a given series not present in another given series:")
sr11 = pd.Series(np.union1d(sr1, sr2))
sr22 = pd.Series(np.intersect1d(sr1, sr2))
result = sr11[~sr11.isin(sr22)]
print(result)

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

num_series = pd.Series(np.take(list('0123456789'), np.random.randint(10, size=40)))


print("Original Series:")
print(num_series)
print("Frequency of each unique value of the said series.")
result = num_series.value_counts()
print(result)

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.

num_series = pd.Series(np.random.randint(1, 5, [15]))


print("Original Series:")
print(num_series)
print("Top 2 Freq:", num_series.value_counts())
result = num_series[~num_series.isin(num_series.value_counts().index[:1])] = 'Other'
print(num_series)

(c) Write a Pandas program to find the positions of numbers that are multiples of 5 of
a given series.

num_series = pd.Series(np.random.randint(1, 10, 9))


print("Original Series:")
print(num_series)
result = np.where(num_series % 5==0)
print("Positions of numbers that are multiples of 5:")
print(result)

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.

series1 = pd.Series(['php', 'python', 'java', 'c#'])


print("Original Series:")
print(series1)
result = series1.map(lambda x: x[0].upper() + x[1:-1] + x[-1].upper())
print("\nFirst and last character of each word to upper case:")
print(result)

(b) Write a Pandas program to compute difference of differences between


consecutive numbers of a given series.

series1 = pd.Series([1, 3, 5, 8, 10, 11, 15])


print("Original Series:")
print(series1)
print("\nDifference of differences between consecutive numbers of the said series:")
print(series1.diff().tolist())
print(series1.diff().diff().tolist())

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.

from dateutil.parser import parse


date_series = pd.Series(['01 Jan 2015', '10-02-2016', '20180307', '2014/05/06', '2016-
04-12', '2019-04-06T11:20'])
print("Original Series:")
print(date_series)
date_series = date_series.map(lambda x: parse(x))
print("Day of month:")
print(date_series.dt.day.tolist())
print("Day of year:")
print(date_series.dt.dayofyear.tolist())
print("Week number:")
print(date_series.dt.weekofyear.tolist())
print("Day of week:")
print(date_series.dt.day_name())

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

exam_data = {'name': ['RISHABH KUMAR', 'SATYAM SINGH', 'SAURABH


MISHRA',
'SHAURYA SHAKYA', 'SHIVAM', '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(df)

2. Write a Pandas program to display a summary of the basic information about a


specified Data Frame and its data.

import pandas as pd
import numpy as np

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

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("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.

exam_data = {'name': ['SHREYANSH', 'SAMRIDDHI', '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("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).

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("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.

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("\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())

8. Write a Pandas program to calculate the mean of all students' scores.

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("\nMean score for each different student in data frame:")
print(df['score'].mean())

25 | P a g e
SUSHANT KUMAR 2101043CS CSE

Assignment 6

1.Write a Program to Implement 8-Puzzle problem using Python.

from collections import deque


def possible_moves(state):
moves = []
zero_index = state.index(0)
if zero_index not in [0, 1, 2]:
moves.append('u')
if zero_index not in [6, 7, 8]:
moves.append('d')
if zero_index not in [0, 3, 6]:
moves.append('l')
if zero_index not in [2, 5, 8]:
moves.append('r')
return moves

def move(state, move):


new_state = state[:]
zero_index = new_state.index(0)
if move == 'u':
new_state[zero_index], new_state[zero_index - 3] = new_state[zero_index - 3],
new_state[zero_index]
elif move == 'd':
new_state[zero_index], new_state[zero_index + 3] = new_state[zero_index + 3],
new_state[zero_index]
elif move == 'l':
new_state[zero_index], new_state[zero_index - 1] = new_state[zero_index - 1],
new_state[zero_index]
elif move == 'r':
new_state[zero_index], new_state[zero_index + 1] = new_state[zero_index + 1],
new_state[zero_index]
return new_state

def bfs_8_puzzle(start_state, goal_state):


visited = set()
queue = deque([(start_state, [])])

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.")

2. Write a Program to Implement 8-Queen problem using Python.

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 solve_queens_problem(board, col):


if col >= N:
return True
for i in range(N):
if is_safe(board, i, col):
board[i][col] = 1

if solve_queens_problem(board, col + 1):


27 | P a g e
SUSHANT KUMAR 2101043CS CSE
return True
board[i][col] = 0
return False

def print_solution(board):
for i in range(N):
for j in range(N):
print(board[i][j], end=" ")
print()

chessboard = [[0] * N for _ in range(N)]


if not solve_queens_problem(chessboard, 0):
print("Solution does not exist")
else:
print_solution(chessboard)

3. Write a Program to Implement BFS & DFS problem using Python.

from collections import defaultdict


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

def add_edge(self, u, v):


self.graph[u].append(v)

def bfs(self, s):


visited = [False] * len(self.graph)
queue = []
queue.append(s)
visited[s] = True

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

def dfs_util(self, v, visited):


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

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

def dfs(self, v):


visited = [False] * len(self.graph)
self.dfs_util(v, 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)

4. Write a Program to Implement Tower of Hanoi problem using Python.

def tower_of_hanoi(n, source, auxiliary, target):


if n == 1:

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

1.Write a program to implement A* search algorithm using python.

from queue import PriorityQueue


class Node:
def __init__(self, state, parent=None, action=None, cost=0, heuristic=0):
self.state = state
self.parent = parent
self.action = action
self.cost = cost
self.heuristic = heuristic
def __lt__(self, other):
return (self.cost + self.heuristic) < (other.cost + other.heuristic)

def heuristic(state, goal):


return ((state[0] - goal[0]) ** 2 + (state[1] - goal[1]) ** 2) ** 0.5

def astar_search(initial_state, goal_state):


open_set = PriorityQueue()
start_node = Node(initial_state, None, None, 0, heuristic(initial_state, goal_state))
open_set.put(start_node)
closed_set = set()

while not open_set.empty():


current_node = open_set.get()

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)

for action in possible_actions(current_node.state):


new_state = apply_action(current_node.state, action)

new_cost = current_node.cost + action_cost(action)

31 | P a g e
SUSHANT KUMAR 2101043CS CSE
new_node = Node(new_state, current_node, action, new_cost,
heuristic(new_state, goal_state))

if new_state not in closed_set:


open_set.put(new_node)
return None

def possible_actions(state):
return [(1, 0), (0, 1)]

def apply_action(state, action):


return state[0] + action[0], state[1] + action[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.")

2.Write a program to implement AO* search algorithm using python.

def Cost(H, condition, weight = 1):


cost = {}
if 'AND' in condition:

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

def update_cost(H, Conditions, weight=1):


Main_nodes = list(Conditions.keys())
Main_nodes.reverse()
least_cost= {}
for key in Main_nodes:
condition = Conditions[key]
print(key,':', Conditions[key],'>>>', Cost(H, condition, weight))
c = Cost(H, condition, weight)
H[key] = min(c.values())
least_cost[key] = Cost(H, condition, weight)
return least_cost

def shortest_path(Start,Updated_cost, H):


Path = Start
if Start in Updated_cost.keys():
Min_cost = min(Updated_cost[Start].values())
key = list(Updated_cost[Start].keys())
values = list(Updated_cost[Start].values())
Index = values.index(Min_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))

3. Write a program to implement Hill climbing algorithm using python.

import random
def evaluate_function(x):
return -1 * (x ** 2)

def get_neighbors(current_solution):
return [current_solution + random.uniform(-0.5, 0.5)]

def hill_climbing(initial_state, max_iterations, get_neighbors, evaluate):


current = initial_state
for _ in range(max_iterations):
neighbors = get_neighbors(current)
if not neighbors:
break
neighbor = max(neighbors, key=evaluate)
if evaluate(neighbor) <= evaluate(current):
break
current = neighbor

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

4. Write a program to Minimax and Alpha-Beta Pruning using python.

import math
def evaluate(state):
return state

def game_over(state, depth):


return depth == 0

def possible_moves(state):
return [state - 1, state + 1]

def minimax(state, depth, maximizing_player):


if depth == 0 or game_over(state, depth):
return evaluate(state)

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

def alpha_beta(state, depth, alpha, beta, maximizing_player):


if depth == 0 or game_over(state, depth):
return evaluate(state)

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)

alpha = max(alpha, eval)


if beta <= alpha:
break
35 | P a g e
SUSHANT KUMAR 2101043CS CSE
return max_eval
else:
min_eval = math.inf
for move in possible_moves(state):
eval = alpha_beta(move, depth - 1, alpha, beta, True)
min_eval = min(min_eval, eval)
beta = min(beta, eval)
if beta <= alpha:
break
return min_eval

initial_state = 10
depth = 4

result_minimax = minimax(initial_state, depth, True)


result_alpha_beta = alpha_beta(initial_state, depth, -math.inf, math.inf, True)
print("Minimax result:", result_minimax)
print("Alpha-Beta Pruning result:", result_alpha_beta)

36 | P a g e
SUSHANT KUMAR 2101043CS CSE

Assignment 8

1.Write a program to solve water jug problem using python.

def water_jug(jug1_capacity, jug2_capacity, target):


jug1 = 0
jug2 = 0
path = []
while jug1 != target and jug2 != target:
if jug2 == jug2_capacity:
jug2 = 0
path.append((jug1, jug2))
elif jug1 == 0:
jug1 = jug1_capacity
path.append((jug1, jug2))
else:
temp = min(jug1, jug2_capacity - jug2)
jug2 += temp
jug1 -= temp
path.append((jug1, jug2))
return path

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)

2.Write a program to shuffle Deck of cards using python.

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]}")

3. Write a program to solve the Monkey Banana problem using python.

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]

matrix = [[1, 3, 1], [2, 4, 3], [5, 2, 1]]


max_bananas_collected = max_bananas(matrix)

print("Maximum bananas collected:", max_bananas_collected)

38 | P a g e
SUSHANT KUMAR 2101043CS CSE

4. Write a program to solve traveling salesman problem using python.

import itertools
def traveling_salesman(graph):
cities = list(range(len(graph)))
min_path = None
min_cost = float('inf')

for path in itertools.permutations(cities):


cost = 0
for i in range(len(path) - 1):
cost += graph[path[i]][path[i+1]]
cost += graph[path[-1]][path[0]]
if cost < min_cost:
min_cost = cost
min_path = path
return min_path, min_cost

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

for num in numbers:


mul_law_1 *= num
mul_law_2 = 1
for i in range(len(numbers) // 2):
mul_law_2 *= numbers[i]
for i in range(len(numbers) // 2, len(numbers)):
mul_law_2 *= numbers[i]
print(f"Multiplication Associative Law: (a * b) * c = {mul_law_1} and a * (b * c) =
{mul_law_2} (Equal: {mul_law_1 == mul_law_2})")

numbers = [2, 3, 4, 5, 6]
associative_law(numbers)

3.De Morgan's Laws:


Write a Python function that implements De Morgan's Laws for two Boolean variables
and returns the results for both AND and OR operations.

def demorgans_laws(bool_a, bool_b):


and_law_1 = not (bool_a and bool_b)
or_law_1 = not bool_a or not bool_b
print(f"De Morgan's Law for AND: not (A and B) = {and_law_1}")

and_law_2 = not bool_a or not bool_b


or_law_2 = not (bool_a or bool_b)
print(f"De Morgan's Law for OR: not (A or B) = {or_law_2}")

bool_a = True
bool_b = False
demorgans_laws(bool_a, bool_b)

4.Law of Excluded Middle:


41 | P a g e
SUSHANT KUMAR 2101043CS CSE
Implement a Python function that illustrates the law of excluded middle by
determining if a given proposition is either true or false.

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.

import matplotlib.pyplot as plt


def adsorption_model(adsorption_capacity, equilibrium_constant):
concentrations = list(range(0, 101))
adsorption = [(adsorption_capacity * x) / (equilibrium_constant + x) for x in
concentrations]

plt.plot(concentrations, adsorption)
plt.xlabel('Concentration')
plt.ylabel('Adsorption')
plt.title('Adsorption Isotherm Curve')
plt.show()

adsorption_capacity = float(input("Enter adsorption capacity: "))


equilibrium_constant = float(input("Enter equilibrium constant: "))
adsorption_model(adsorption_capacity, equilibrium_constant)

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})"

logical_expression = "A and B"


simplified_expression = double_negation(logical_expression)
print(f"The double negation of {logical_expression} is: {simplified_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

def modus_ponens(knowledge_base, implication):


if knowledge_base and implication[0]:
if knowledge_base in implication[1]:
return True
return False

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.

def modus_tollens(conditional_statement, negation_consequent):


if conditional_statement[1] == negation_consequent and conditional_statement[0]
!= negation_consequent:
return f"Negation of {conditional_statement[0]}"
return "Does not imply 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

Predicate Logic and Python:


1.Implement a Python function that converts a given predicate logic expression into a
truth table.

from itertools import product

def truth_table(expression, variables):


header = variables + [expression]
table = [header]
for assignment in product([True, False], repeat=len(variables)):
assignment_result = list(assignment)
assignment_result.append(eval(expression, dict(zip(variables, assignment))))
table.append(assignment_result)
return table

predicate = "(A and B) or (not A)"


variables = ['A', 'B']
result_table = truth_table(predicate, variables)

for row in result_table:


print(row)

Quantifiers:
2. Write a Python program that checks if a given predicate logic statement with
universal quantifiers is true for a given domain.

from itertools import product


def P(x):
return x > 0

def Q(y):
46 | P a g e
SUSHANT KUMAR 2101043CS CSE
return y % 2 == 0

def check_universal(statement, variables, domain):


for values in product(*domain):
variable_dict = dict(zip(variables, values))
eval_statement = statement
for var, val in variable_dict.items():
eval_statement = eval_statement.replace(var, str(val))
if not eval(eval_statement, globals(), {pred.__name__: pred for pred in [P, Q]}):
return False
return True

universal_statement = "P(x) and Q(y)"


variables = ['x', 'y']
domain = [range(-5, 6), range(10)]

is_true = check_universal(universal_statement, variables, domain)


print(f"Is the statement universally true? {is_true}")

3.Create a Python script that determines if a predicate logic statement with existential
quantifiers is satisfied in a set of data.

from itertools import product

def P(x):
return x > 0

def Q(y):
return y % 2 == 0

def check_existential(statement, variables, domain):


for values in product(*domain):
variable_dict = dict(zip(variables, values))
eval_statement = statement
for var, val in variable_dict.items():
eval_statement = eval_statement.replace(var, str(val))

if eval(eval_statement, globals(), {pred.__name__: pred for pred in [P, Q]}):


return True
return False

47 | P a g e
SUSHANT KUMAR 2101043CS CSE

existential_statement = "P(x) and Q(y)"


variables = ['x', 'y']
domain = [range(-5, 6), range(10)]
is_satisfied = check_existential(existential_statement, variables, domain)
print(f"Does the statement hold for some value in the domain? {is_satisfied}")

48 | P a g e

You might also like