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

OSDBMS

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

OSDBMS

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/ 59

ASSIGNMENT 1

1. Write a python program to display a particular month of a year using


calendar.
Code:
import calendar
def display_month(year, month):
print(calendar.month(year, month))

display_month(2023, 11)

Output:

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


Code:
def print_all_months(year):
for month in range(1, 13):
print(calendar.month_name[month], year)

print_all_months(2023)
Output:
3. Write a python program to print date, time for today and now.
Code:
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()
Output:

4. Write a python program to add some days to your present date and
print the date added.
Code:
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)

Output:
ASSIGNMENT 2
1. Write a python program to display a particular month of a year using
calendar module.
Code:
import calendar
year = 2023
month = 10
print(calendar.month(year, month))

Output:

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


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

Output:
3. Write a python program to print a number is positive/negative using if-
else.
Code:
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")

Output:

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


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

Output:

5. Write a python program to read a number and display corresponding day


using if-else.
Code:
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:
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.")

Output:
6. Write a python program to check whether the given string is palindrome
or not.
Code:
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.")

Output:

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


functions.
Code:
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))
Output:

8. Write a python function that takes two lists and returns True if they are
equal otherwise false.
Code:
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))

Output:
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.
Code:
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)

Output:

(b) We create an empty array of 4X2 and a full array of 4X3 of INTEGER
and FLOAT type.
Code:
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)

Output:

(c) We create an empty array of 3X3 and a full array of 5X3 of FLOAT
type.
Code:
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)

Output:
2. (a) Creating a one-dimensional array with zeros using numpy.zeros().
Code:
zeroes_1d = np.zeros(5)
print("One-dimensional array of zeros:")
print(zeroes_1d)

Output:

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


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

Output:

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


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

Output:
(d)NumPy zeros array with an integer data type.
Code:
zeroes_int = np.zeros((2, 2), dtype=int)
print("Zeros array with integer data type:")
print(zeroes_int)

Output:

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


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

Output:
3. How to check whether specified values are present in NumPy array.
Code:
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)

Output:

4. NumPy – Fibonacci Series using Binet Formula.


(a)To find first 5 Fibonacci numbers.
Code:
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)

Output:
(b)To find first ‘n’ Fibonacci numbers.
Code:
n = 10
first_n_fib = fibonacci_binet(n)
print(f"First {n} Fibonacci numbers using Binet's formula:", first_n_fib)

Output:

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

Output:
ASSIGNMENT 4
1. (a) Write a Pandas program to create a subset of a given series based on
value and condition.
Code:
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)

Output:

(b) Write a Pandas program to create the mean and standard deviation of
the
data of a given Series.
Code:
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())

Output:

(c) Write a Pandas program to get the items of a given series not present
in
another given series.
Code:
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)

Output:

(d) Write a Pandas program to get the items which are not common of
two given series.
Code:
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)

Output:
(e) Write a Pandas program to compute the minimum, 25th percentile,
median,
75th, and maximum of a given series.
Code:
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)

Output:
2. (a) Write a Pandas program to calculate the frequency counts of each
unique
value of a given series.
Code:

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)

Output:
(b) Write a Pandas program to display most frequent value in a given
series and replace everything else as 'Other' in the series.
Code:
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)

Output:
(c) Write a Pandas program to find the positions of numbers that are
multiples of 5 of a given series.
Code:
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)

Output:
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.
Code:
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)

Output:

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


between
consecutive numbers of a given series.
Code:
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())

Output:

(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.
Code:
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())
Output:
ASSIGNMENT 5
1. Write a Pandas program to create and display a Data Frame from a
specified dictionary data which has the index labels.
Code:
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)

Output:

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


about a specified Data Frame and its data.
Code:
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']

df = pd.DataFrame(exam_data , index=labels)
print(df.info())

Output:

3. Write a Pandas program to select the 'name' and 'score' columns from
the following Data Frame.
Code:
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']])
Output:

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.
Code:
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]])

Output:

5. Write a Pandas program to select the rows the score is between 15


and 20 (inclusive).
Code:
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)])

Output:

6. Write a Pandas program to change the score in row 'd' to 11.5.


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

Output:
7. Write a Pandas program to calculate the sum of the examination
attempts by the students.
Code:
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())
Output:

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


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

Output:
ASSIGNMENT 6
1.Write a Program to Implement 8-Puzzle problem using Python.
Code:
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()

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

Output:

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


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


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)

Output:

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


Code:
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=" ")

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)

Output:

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


Code:
def tower_of_hanoi(n, source, auxiliary, target):
if n == 1:
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')

Output:
ASSIGNMENT 7

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


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


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

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

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

Output:
3. Write a program to implement Hill climbing algorithm using python.
Code:
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)

Output:
4. Write a program to Minimax and Alpha-Beta Pruning using python.
Code:
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
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)

Output:
ASSIGNMENT 8

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


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

Output:

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


Code:
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:")
for card in deck:
print(f"{card[0]} of {card[1]}")

Output:

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


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

Output:

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


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

Output:
ASSIGNMENT 9

1.Commutative Law:
Write a Python function to demonstrate the commutative law for
addition and multiplication using user input.
Code:
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()

Output:

2.Associative Law:
Create a Python program that verifies the associative law for addition and
multiplication with a list of numbers.
Code:
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

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)

Output:

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

Output:

4.Law of Excluded Middle:


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)

Output:
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.
Code:
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)

Output:
2.Double Negation:
Write a Python function to apply double negation to a logical expression
represented as a string and return the simplified expression.
Code:
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}")

Output:

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

Output:

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.
Code:
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)
Output:
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.
Code:
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)

Output:

ASSIGNMENT 11
Predicate Logic and Python:

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

def truthTable(expression,inputs=2):
print("Boolean Expression:")
print(" X = " + expression.upper())
expression = expression.lower()

expression = expression.replace("and","&")
expression = expression.replace("xor","^")
expression = expression.replace("or","|")
expression = expression.replace("not","~")

print("\nTruth Table:")
if inputs==2:
print(" -------------")
print(" | A | B | X |")
print(" -------------")

for a in range(0,2):
for b in range(0,2):
x = eval(expression)
print(" | " + str(a) + " | " + str(b) + " | " + str(x) + " |" )
print(" -------------")

elif inputs==3:
print(" -----------------")
print(" | A | B | C | X |")
print(" -----------------")

for a in range(0,2):
for b in range(0,2):
for c in range(0,2):
x = eval(expression)
print(" | " + str(a) + " | " + str(b) + " | " + str(c) + " | " + str(x) + " |" )
print(" -----------------")

elif inputs==4:
print(" ---------------------")
print(" | A | B | C | D | X |")
print(" ---------------------")

for a in range(0,2):
for b in range(0,2):
for c in range(0,2):
for d in range(0,2):
x = eval(expression)
print(" | " + str(a) + " | " + str(b) + " | " + str(c) + " | " + str(d) + " | " + str(x) + " |" )
print(" ---------------------")

##############################################

expression = "A AND NOT (B XOR C)"


truthTable(expression,3)

Quantifiers:

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 evaluate(predicate, domain):

variables = list(predicate._code_.co_varnames)

possible_combinations = product(domain, repeat=len(variables))

for values in possible_combinations:

if not predicate(*values):

return False

return True

# Example usage:

predicate_statement = lambda x: x > 0 # Example statement: x > 0

domain = [1, 2, 3, 4, -5] # Example domain, replace with your own domain
result = evaluate(predicate_statement, domain)

if result:

print("The predicate logic statement is true for the given domain.")

else:

print("The predicate logic statement is not true for the given domain.")

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 evaluate(statement, data):


variables = list(set([char for char in statement if char.isalpha()]))
possible_combinations = product([True, False], repeat=len(variables))

for values in possible_combinations:


var_values = dict(zip(variables, values))
if eval(statement, var_values):
if all(eval(statement, {**var_values, **data_point}) for data_point in data):
return True
return False

# Example usage:
predicate_statement = "(P and Q) or R" # Example statement, replace with your own
statement
data = [
{"P": True, "Q": True, "R": False},
{"P": False, "Q": True, "R": True},
{"P": True, "Q": False, "R": True}
] # Example set of data, replace with your own data

result = evaluate(predicate_statement, data)


if result:
print("The predicate logic statement is satisfied in the set of data.")
else:
print("The predicate logic statement is not satisfied in the set of data.")

You might also like