Added all the codes.
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
# Assignment-A1 (DFS | BFS) -> Alternative
|
||||
|
||||
"""
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: Implement depth first search algorithm and Breadth First Search algorithm, Use an undirected graph and develop a recursive algorithm for searching all the vertices of a graph or tree data structure.
|
||||
|
||||
Code from ArtificialIntelligence (SPPU - Third Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-te-comp-content/ArtificialIntelligence
|
||||
"""
|
||||
|
||||
# Uses queue for BFS & stack for DFS
|
||||
|
||||
# BEGINNING OF CODE
|
||||
def bfs(graph, start):
|
||||
visited = [False] * len(graph)
|
||||
queue = [start]
|
||||
|
||||
while queue:
|
||||
node = queue.pop(0)
|
||||
if not visited[node]:
|
||||
print(node, end=" ")
|
||||
visited[node] = True
|
||||
|
||||
for neighbour in range(len(graph)):
|
||||
if graph[node][neighbour] == 1 and not visited[neighbour]:
|
||||
queue.append(neighbour)
|
||||
|
||||
def dfs(graph, start):
|
||||
visited = [False] * len(graph)
|
||||
stack = [start]
|
||||
|
||||
while stack:
|
||||
node = stack.pop()
|
||||
if visited[node] != True:
|
||||
print(node, end=" ")
|
||||
visited[node] = True
|
||||
|
||||
for neighbour in range(len(graph) - 1, -1, -1):
|
||||
if graph[node][neighbour] == 1 and visited[neighbour] != True:
|
||||
stack.append(neighbour)
|
||||
|
||||
graph = [
|
||||
# A B C D E F
|
||||
[ 0, 1, 1, 0, 0, 0], # A
|
||||
[ 1, 0, 0, 1, 1, 0], # B
|
||||
[ 1, 0, 0, 0, 0, 1], # C
|
||||
[ 0, 1, 0, 0, 0, 0], # D
|
||||
[ 0, 1, 0, 0, 0, 1], # E
|
||||
[ 0, 0, 1, 0, 1, 0] # F
|
||||
] # Might need to take user input for this. Hard coded values only for testing.
|
||||
|
||||
print("Breadth First Search:\t", end=" ")
|
||||
bfs(graph, 0)
|
||||
print("\nDepth First Search:\t", end=" ")
|
||||
dfs(graph, 0)
|
||||
# END OF CODE
|
||||
@@ -0,0 +1,86 @@
|
||||
# Assignment-A2 (A* Algorithm)
|
||||
|
||||
"""
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: Implement A star Algorithm for any game search problem.
|
||||
|
||||
Code from ArtificialIntelligence (SPPU - Third Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-te-comp-content/ArtificialIntelligence
|
||||
"""
|
||||
|
||||
# This code directly implements A* algorithm for finding the optimal
|
||||
# solution. It is NOT implemented for any game search problem.
|
||||
|
||||
# A* implementation for 8 puzzle problem can be found in the "Codes" folder
|
||||
# and maze problem solving can be found in the "Alternatives" folder.
|
||||
|
||||
# BEGINNING OF CODE
|
||||
import heapq
|
||||
|
||||
def a_star(graph, start, goal, heuristic):
|
||||
g = {v: float('inf') for v in graph}
|
||||
f = {v: float('inf') for v in graph}
|
||||
parent = {v: None for v in graph}
|
||||
|
||||
g[start] = 0
|
||||
f[start] = heuristic[start]
|
||||
|
||||
open_list = [(f[start], start)]
|
||||
|
||||
while open_list:
|
||||
_, current = heapq.heappop(open_list)
|
||||
|
||||
if current == goal:
|
||||
return reconstruct_path(parent, goal, g[goal])
|
||||
|
||||
for neighbor, weight in graph[current]:
|
||||
tentative_g = g[current] + weight
|
||||
if tentative_g < g[neighbor]:
|
||||
parent[neighbor] = current
|
||||
g[neighbor] = tentative_g
|
||||
f[neighbor] = tentative_g + heuristic[neighbor]
|
||||
heapq.heappush(open_list, (f[neighbor], neighbor))
|
||||
|
||||
return []
|
||||
|
||||
def reconstruct_path(parent, goal, cost):
|
||||
path = []
|
||||
while goal:
|
||||
path.append(goal)
|
||||
goal = parent[goal]
|
||||
path.reverse()
|
||||
print("Path cost:", cost)
|
||||
return path
|
||||
|
||||
def main():
|
||||
n = int(input("Enter number of vertices: "))
|
||||
print("Enter vertex names (e.g., A B C ...):")
|
||||
vertices = input().split()
|
||||
|
||||
graph = {v: [] for v in vertices}
|
||||
|
||||
m = int(input("Enter number of edges: "))
|
||||
print("Enter edges (format: source destination weight):")
|
||||
for _ in range(m):
|
||||
u, v, w = input().split()
|
||||
w = int(w)
|
||||
graph[u].append((v, w))
|
||||
# graph[v].append((u, w)) # Uncomment for undirected graph
|
||||
|
||||
heuristic = {}
|
||||
print("Enter heuristic values (e.g., A 4 B 2 ...):")
|
||||
for _ in range(n):
|
||||
name, h = input().split()
|
||||
heuristic[name] = int(h)
|
||||
|
||||
start = input("Enter start vertex: ")
|
||||
goal = input("Enter goal vertex: ")
|
||||
|
||||
path = a_star(graph, start, goal, heuristic)
|
||||
if path:
|
||||
print("Optimal path:", ' -> '.join(path))
|
||||
else:
|
||||
print("No path found.")
|
||||
|
||||
main()
|
||||
# END OF CODE
|
||||
@@ -0,0 +1,113 @@
|
||||
# Assignment-A2 (A* Algorithm for Game Search)
|
||||
|
||||
"""
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: Implement A star Algorithm for any game search problem.
|
||||
|
||||
Code from ArtificialIntelligence (SPPU - Third Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-te-comp-content/ArtificialIntelligence
|
||||
"""
|
||||
|
||||
# This code implements A* algorithm for maze game solving since the problem
|
||||
# statement in our syllabus (but not our handout) demands implementing A*
|
||||
# algorithm for any game search problem.
|
||||
|
||||
# A* implementation for 8 puzzle problem can be found in the "Codes" folder
|
||||
# and direct implementation can be found in the "Alternatives" folder.
|
||||
|
||||
# BEGINNING OF CODE
|
||||
print("Maze game solving")
|
||||
|
||||
# Directions: up, down, left, right
|
||||
DIRECTIONS = [(-1, 0), (1, 0), (0, -1), (0, 1)]
|
||||
|
||||
class Node:
|
||||
def __init__(self, x, y, g, h, parent=None):
|
||||
self.x = x
|
||||
self.y = y
|
||||
self.g = g # cost to reach the node from the start
|
||||
self.h = h # estimated cost from node to goal (heuristic)
|
||||
self.f = g + h
|
||||
self.parent = parent
|
||||
|
||||
def heuristic(x1, y1, x2, y2): # Manhattan distance
|
||||
return abs(x1 - x2) + abs(y1 - y2)
|
||||
|
||||
def a_star(grid, start, goal):
|
||||
open_list = []
|
||||
closed_set = set()
|
||||
|
||||
start_node = Node(start[0], start[1], 0, heuristic(start[0], start[1], goal[0], goal[1])) #Node(x, y, g, h)
|
||||
open_list.append(start_node)
|
||||
|
||||
while open_list:
|
||||
# Find node with lowest f in open_list
|
||||
current_node = min(open_list, key=lambda node: node.f)
|
||||
open_list.remove(current_node)
|
||||
|
||||
if (current_node.x, current_node.y) == goal:
|
||||
path = []
|
||||
while current_node:
|
||||
path.append((current_node.x, current_node.y))
|
||||
current_node = current_node.parent
|
||||
return path[::-1]
|
||||
|
||||
closed_set.add((current_node.x, current_node.y))
|
||||
|
||||
for direction in DIRECTIONS:
|
||||
nx, ny = current_node.x + direction[0], current_node.y + direction[1]
|
||||
if 0 <= nx < len(grid) and 0 <= ny < len(grid[0]) and grid[nx][ny] == 1 and (nx, ny) not in closed_set:
|
||||
g = current_node.g + 1
|
||||
h = heuristic(nx, ny, goal[0], goal[1])
|
||||
neighbor = Node(nx, ny, g, h, current_node)
|
||||
open_list.append(neighbor)
|
||||
|
||||
return None
|
||||
|
||||
def get_user_input():
|
||||
rows = int(input("Enter number of rows: "))
|
||||
cols = int(input("Enter number of columns: "))
|
||||
grid = []
|
||||
print("Enter the grid row by row (1 for walkable, 0 for blocked):")
|
||||
for i in range(rows):
|
||||
row = list(map(int, input(f"Row {i+1}: ").split()))
|
||||
grid.append(row)
|
||||
|
||||
start = tuple(map(int, input("Enter start point (row col): ").split()))
|
||||
goal = tuple(map(int, input("Enter goal point (row col): ").split()))
|
||||
return grid, start, goal
|
||||
|
||||
def main():
|
||||
# Get the user input for the grid, start, and goal positions
|
||||
grid, start, goal = get_user_input()
|
||||
|
||||
# Call the A* algorithm to find the path
|
||||
path = a_star(grid, start, goal)
|
||||
|
||||
# Print the result based on whether a path is found or not
|
||||
if path:
|
||||
print("Path found:", path)
|
||||
else:
|
||||
print("No path found.")
|
||||
|
||||
main()
|
||||
# END OF CODE
|
||||
|
||||
# NOTE: IN THE MATRIX FORMED (ROWS+COLUMN WALA), THE TOP LEFT CELL HAS VALUE (0,0).
|
||||
# For eg.: If you're making a 3x3 matrix, top left corner will have value (0,0)
|
||||
# and, bottom right corner will have value (2,2).
|
||||
|
||||
"""
|
||||
SAMPLE OUTPUT:
|
||||
|
||||
Maze game solving
|
||||
Enter number of rows: 3
|
||||
Enter number of columns: 3
|
||||
Enter the grid row by row (1 for walkable, 0 for blocked):
|
||||
Row 1: 1 0 1
|
||||
Row 2: 1 1 1
|
||||
Row 3: 0 0 1
|
||||
Enter start point (row col): 0 0
|
||||
Enter goal point (row col): 2 2
|
||||
Path found: [(0, 0), (1, 0), (1, 1), (1, 2), (2, 2)]
|
||||
"""
|
||||
@@ -0,0 +1,97 @@
|
||||
# Assignment-3 (Alternative)
|
||||
|
||||
"""
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: Implement Greedy search algorithm for any of the following application:
|
||||
I. Selection Sort
|
||||
V. Prim's Minimal Spanning Tree Algorithm
|
||||
|
||||
Code from ArtificialIntelligence (SPPU - Third Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-te-comp-content/ArtificialIntelligence
|
||||
"""
|
||||
|
||||
# BEGINNING OF CODE
|
||||
numbers = []
|
||||
graph = []
|
||||
|
||||
# BEGINNING OF SELECTION SORT
|
||||
# Input numbers
|
||||
def input_number():
|
||||
total = int(input("Enter total numbers: "))
|
||||
for i in range(total):
|
||||
val = float(input("Enter number: "))
|
||||
numbers.append(val)
|
||||
print("Numbers you entered:", numbers)
|
||||
|
||||
# Perform selection sort
|
||||
def selection_sort():
|
||||
for i in range(len(numbers)):
|
||||
for j in range(i, len(numbers)):
|
||||
if numbers[j] < numbers[i]:
|
||||
numbers[i], numbers[j] = numbers[j], numbers[i]
|
||||
print("Sorted numbers:", numbers)
|
||||
# END OF SELECTION SORT
|
||||
|
||||
# BEGINNING OF PRIM'S MST
|
||||
def prims_mst(graph):
|
||||
n = len(graph)
|
||||
selected = [False] * n
|
||||
no_of_edges = 0
|
||||
selected[0] = True
|
||||
|
||||
print("Edge : Weight")
|
||||
while no_of_edges < n - 1:
|
||||
minimum = 999
|
||||
x = 0
|
||||
y = 0
|
||||
|
||||
for i in range(n):
|
||||
if selected[i]:
|
||||
for j in range(n):
|
||||
if not selected[j] and graph[i][j] != 999 and i != j:
|
||||
if minimum > graph[i][j]:
|
||||
minimum = graph[i][j]
|
||||
x = i
|
||||
y = j
|
||||
print(f"{x} - {y} : {graph[x][y]}")
|
||||
selected[y] = True
|
||||
no_of_edges += 1
|
||||
|
||||
# Function to input graph as adjacency matrix
|
||||
def input_graph():
|
||||
V = int(input("Enter number of vertices: "))
|
||||
print("Enter adjacency matrix row by row:")
|
||||
for i in range(V):
|
||||
row = list(map(int, input(f"Row {i}: ").split()))
|
||||
graph.append(row)
|
||||
# END OF PRIM'S MST
|
||||
|
||||
|
||||
# Main menu-driven function
|
||||
def main():
|
||||
while True:
|
||||
print("\nMenu:")
|
||||
print("1. Input numbers and perform selection sort")
|
||||
print("2. Perform selection sort")
|
||||
print("3. Input graph")
|
||||
print("4. Run Prim's MST algorithm")
|
||||
print("5. Exit")
|
||||
|
||||
choice = int(input("Enter your choice: "))
|
||||
|
||||
if choice == 1:
|
||||
input_number()
|
||||
elif choice == 2:
|
||||
selection_sort()
|
||||
elif choice == 3:
|
||||
input_graph()
|
||||
elif choice == 4:
|
||||
prims_mst(graph)
|
||||
elif choice == 5:
|
||||
print("Exiting...")
|
||||
break
|
||||
else:
|
||||
print("Invalid choice! Please try again.")
|
||||
|
||||
main()
|
||||
# END OF CODE
|
||||
@@ -0,0 +1,64 @@
|
||||
# Assignment-3.V (Prim's Minimal Spanning Tree Algorithm)
|
||||
|
||||
"""
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: Implement Greedy search algorithm for any of the following application:
|
||||
V. Prim's Minimal Spanning Tree Algorithm
|
||||
|
||||
Code from ArtificialIntelligence (SPPU - Third Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-te-comp-content/ArtificialIntelligence
|
||||
"""
|
||||
|
||||
# BEGINNING OF CODE
|
||||
graph = []
|
||||
def prims_mst(graph):
|
||||
n = len(graph)
|
||||
selected = [False] * n
|
||||
no_of_edges = 0
|
||||
selected[0] = True
|
||||
|
||||
print("Edge : Weight")
|
||||
while no_of_edges < n - 1:
|
||||
minimum = 999
|
||||
x = 0
|
||||
y = 0
|
||||
|
||||
for i in range(n):
|
||||
if selected[i]==True:
|
||||
for j in range(n):
|
||||
if not selected[j] and graph[i][j] != 999 and i != j:
|
||||
if minimum > graph[i][j]:
|
||||
minimum = graph[i][j]
|
||||
x = i
|
||||
y = j
|
||||
print(f"{x} - {y} : {graph[x][y]}")
|
||||
selected[y] = True
|
||||
no_of_edges += 1
|
||||
|
||||
def input_graph():
|
||||
V = int(input("Enter number of vertices: "))
|
||||
print("Enter adjacency matrix of Graph row by row:")
|
||||
for i in range(V):
|
||||
row = list(map(int, input(f"Row {i}: ").split()))
|
||||
graph.append(row)
|
||||
def main():
|
||||
while True:
|
||||
print("\nMenu:")
|
||||
print("1. Input graph")
|
||||
print("2. Run Prim's MST algorithm")
|
||||
print("3. Exit")
|
||||
|
||||
choice = int(input("Enter your choice: "))
|
||||
|
||||
if choice == 1:
|
||||
input_graph()
|
||||
elif choice == 2:
|
||||
prims_mst(graph)
|
||||
elif choice == 3:
|
||||
print("Exiting...")
|
||||
break
|
||||
else:
|
||||
print("Invalid choice! Please try again.")
|
||||
|
||||
main()
|
||||
# END OF CODE
|
||||
@@ -0,0 +1,107 @@
|
||||
# Assignment-B5 (Chatbot)
|
||||
|
||||
"""
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: Develop an elementary chatbot for any suitable customer interaction application.
|
||||
|
||||
Code from ArtificialIntelligence (SPPU - Third Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-te-comp-content/ArtificialIntelligence
|
||||
"""
|
||||
|
||||
# BEGINNING OF CODE
|
||||
import nltk
|
||||
from nltk.chat.util import Chat, reflections
|
||||
|
||||
pairs=[
|
||||
[
|
||||
r"my name is (.)",
|
||||
["Hello %1, How are you"]
|
||||
],
|
||||
[
|
||||
r"Hi|Hello|Hey there|Hola",
|
||||
["Hello my name is Hiesenberg"]
|
||||
],
|
||||
[
|
||||
r"what is your name ?",
|
||||
["I am a bot created by Heisenbergwhat. you can call me crazy!",]
|
||||
],
|
||||
[
|
||||
r"how are you ?",
|
||||
["I'm doing good How about You ?",]
|
||||
],
|
||||
[
|
||||
r"sorry (.*)",
|
||||
["Its alright","Its OK, never mind",]
|
||||
],
|
||||
[
|
||||
r"I am fine",
|
||||
["Great to hear that, How can I help you?",]
|
||||
],
|
||||
[
|
||||
r"I (.*) good",
|
||||
["Nice to hear that","How can I help you?:)",]
|
||||
],
|
||||
[
|
||||
r"(.*) age?",
|
||||
["I'm a computer program dude Seriously you are asking me this?",]
|
||||
],
|
||||
[
|
||||
r"what (.*) want ?",
|
||||
["Make me an offer I can't refuse",]
|
||||
],
|
||||
[
|
||||
r"(.*) created ?",
|
||||
["Raghav created me using Python's NLTK library ","top secret ;)",]
|
||||
],
|
||||
[
|
||||
r"(.*) (location|city) ?",
|
||||
['Pune, Maharashtra',]
|
||||
],
|
||||
[
|
||||
r"how is weather in (.*)?",
|
||||
["Weather in %1 is awesome like always","Too hot man here in %1","Too cold man here in %1","Never even heard about %1"]
|
||||
],
|
||||
[
|
||||
r"i work in (.*)?",
|
||||
["%1 is an Amazing company, I have heard about it. But they are in huge loss these days.",]
|
||||
],
|
||||
[
|
||||
r"(.*)raining in (.*)",
|
||||
["No rain since last week here in %2","Damn its raining too much here in %2"]
|
||||
],
|
||||
[
|
||||
r"how (.*) health(.*)",
|
||||
["I'm a computer program, so I'm always healthy ",]
|
||||
],
|
||||
[
|
||||
r"(.*) (sports|game) ?",
|
||||
["I'm a very big fan of Football",]
|
||||
],
|
||||
[
|
||||
r"who (.*) sportsperson ?",
|
||||
["Messy","Ronaldo","Roony"]
|
||||
],
|
||||
[
|
||||
r"who (.*) (moviestar|actor)?",
|
||||
["Brad Pitt"]
|
||||
],
|
||||
[
|
||||
r"I am looking for online guides and courses to learn data science, can you suggest?",
|
||||
["Crazy_Tech has many great articles with each step explanation along with code, you can explore"]
|
||||
],
|
||||
[
|
||||
r"quit",
|
||||
["Thank you for using our intelligence services"]
|
||||
],
|
||||
|
||||
|
||||
]
|
||||
|
||||
def chat():
|
||||
print("Hey there! I am Heisenberg at your service")
|
||||
chat = Chat(pairs)
|
||||
chat.converse()
|
||||
|
||||
if __name__== "__main__":
|
||||
chat()
|
||||
# END OF CODE
|
||||
@@ -0,0 +1,129 @@
|
||||
# Assignment-C6 (Expert System - Airline Scheduling and Cargo Schedules)
|
||||
|
||||
"""
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: Implement any one of the following Expert System
|
||||
VI. Airline scheduling and cargo schedules
|
||||
|
||||
Code from ArtificialIntelligence (SPPU - Third Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-te-comp-content/ArtificialIntelligence
|
||||
"""
|
||||
|
||||
"""
|
||||
Install required package: experta
|
||||
pip install experta
|
||||
"""
|
||||
|
||||
# BEGINNING OF CODE
|
||||
from experta import *
|
||||
|
||||
class Flight(Fact):
|
||||
"""Flight details"""
|
||||
flight_id: str
|
||||
aircraft_type: str
|
||||
available: bool
|
||||
pilot_available: bool
|
||||
destination: str
|
||||
|
||||
class Cargo(Fact):
|
||||
"""Cargo details"""
|
||||
cargo_id: str
|
||||
weight: float
|
||||
category: str # e.g., perishable, fragile, standard
|
||||
priority: str # high, medium, low
|
||||
destination: str
|
||||
|
||||
# Define the Expert System
|
||||
class AirlineExpertSystem(KnowledgeEngine):
|
||||
|
||||
@Rule(Cargo(weight=P(lambda x: x > 10000)))
|
||||
def reject_heavy_cargo(self):
|
||||
print("Cargo rejected: Weight exceeds limit (10,000kg).")
|
||||
|
||||
@Rule(
|
||||
Flight(available=True, pilot_available=True, destination=MATCH.dest),
|
||||
Cargo(destination=MATCH.dest, priority='high')
|
||||
)
|
||||
def schedule_high_priority(self, dest):
|
||||
print(f"High priority cargo scheduled to {dest} on available flight.")
|
||||
|
||||
@Rule(
|
||||
Flight(available=True, pilot_available=True, destination=MATCH.dest),
|
||||
Cargo(destination=MATCH.dest, category='perishable')
|
||||
)
|
||||
def schedule_perishable(self, dest):
|
||||
print(f"Perishable cargo assigned to next available flight to {dest}.")
|
||||
|
||||
@Rule(
|
||||
Flight(available=True, pilot_available=True, destination=MATCH.dest),
|
||||
Cargo(destination=MATCH.dest)
|
||||
)
|
||||
def schedule_standard(self, dest):
|
||||
print(f"Standard cargo scheduled to {dest}.")
|
||||
|
||||
@Rule(Flight(available=False))
|
||||
def no_flight(self):
|
||||
print("No flight available currently.")
|
||||
|
||||
@Rule(Flight(pilot_available=False))
|
||||
def no_pilot(self):
|
||||
print("No pilot available for the flight.")
|
||||
|
||||
# Function to get user input and run the system
|
||||
def run_system():
|
||||
engine = AirlineExpertSystem()
|
||||
engine.reset()
|
||||
|
||||
print("\nEnter Flight Details")
|
||||
flight_id = input("Flight ID: ")
|
||||
aircraft_type = input("Aircraft Type: ")
|
||||
available = input("Is Flight Available? (yes/no): ").lower() == 'yes'
|
||||
pilot_available = input("Is Pilot Available? (yes/no): ").lower() == 'yes'
|
||||
destination = input("Destination: ")
|
||||
|
||||
flight_fact = Flight(
|
||||
flight_id=flight_id,
|
||||
aircraft_type=aircraft_type,
|
||||
available=available,
|
||||
pilot_available=pilot_available,
|
||||
destination=destination
|
||||
)
|
||||
print(f"Declaring Flight Fact: {flight_fact}")
|
||||
engine.declare(flight_fact)
|
||||
|
||||
print("\nEnter Cargo Details")
|
||||
cargo_id = input("Cargo ID: ")
|
||||
|
||||
# Input validation for weight
|
||||
while True:
|
||||
try:
|
||||
weight = float(input("Weight (in kg): "))
|
||||
if weight <= 0:
|
||||
raise ValueError("Weight must be a positive number.")
|
||||
break
|
||||
except ValueError as e:
|
||||
print(e)
|
||||
|
||||
category = input("Category (perishable/fragile/standard): ").lower()
|
||||
priority = input("Priority (high/medium/low): ").lower()
|
||||
cargo_destination = input("Destination: ")
|
||||
|
||||
cargo_fact = Cargo(
|
||||
cargo_id=cargo_id,
|
||||
weight=weight,
|
||||
category=category,
|
||||
priority=priority,
|
||||
destination=cargo_destination
|
||||
)
|
||||
print(f"Declaring Cargo Fact: {cargo_fact}")
|
||||
engine.declare(cargo_fact)
|
||||
|
||||
print("\nRunning Expert System...\n")
|
||||
try:
|
||||
engine.run()
|
||||
except Exception as e:
|
||||
print(f"An error occurred: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_system()
|
||||
# END OF CODE
|
||||
@@ -0,0 +1,69 @@
|
||||
# Assignment-C6 (Expert System - Employee Performance Evaluation)
|
||||
|
||||
"""
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: Implement any one of the following Expert System
|
||||
IV. Employee performance evaluation
|
||||
|
||||
Code from ArtificialIntelligence (SPPU - Third Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-te-comp-content/ArtificialIntelligence
|
||||
"""
|
||||
|
||||
# BEGINNING OF CODE
|
||||
def evaluate_employee():
|
||||
print("🔍 Employee Performance Evaluation System\n")
|
||||
|
||||
# Input section
|
||||
attendance = input("1. Attendance (Good / Average / Poor): ").strip().lower()
|
||||
project = input("2. Project Completion (On Time / Delayed / Incomplete): ").strip().lower()
|
||||
teamwork = input("3. Teamwork (Excellent / Good / Poor): ").strip().lower()
|
||||
punctuality = input("4. Punctuality (Always on time / Often late): ").strip().lower()
|
||||
|
||||
# Score system
|
||||
score = 0
|
||||
|
||||
# Attendance score
|
||||
if attendance == "good":
|
||||
score += 3
|
||||
elif attendance == "average":
|
||||
score += 2
|
||||
elif attendance == "poor":
|
||||
score += 0
|
||||
|
||||
# Project completion score
|
||||
if project == "on time":
|
||||
score += 3
|
||||
elif project == "delayed":
|
||||
score += 1
|
||||
elif project == "incomplete":
|
||||
score += 0
|
||||
|
||||
# Teamwork score
|
||||
if teamwork == "excellent":
|
||||
score += 3
|
||||
elif teamwork == "good":
|
||||
score += 2
|
||||
elif teamwork == "poor":
|
||||
score += 0
|
||||
|
||||
# Punctuality score
|
||||
if punctuality == "always on time":
|
||||
score += 2
|
||||
elif punctuality == "often late":
|
||||
score += 0
|
||||
|
||||
# Decision logic
|
||||
print("\n📊 Evaluation Result:",score)
|
||||
|
||||
if score >= 9:
|
||||
print("⭐ Performance: Excellent")
|
||||
elif score >= 6:
|
||||
print("✅ Performance: Good")
|
||||
elif score >= 3:
|
||||
print("⚠️ Performance: Needs Improvement")
|
||||
else:
|
||||
print("❌ Performance: Poor")
|
||||
|
||||
# Run the expert system
|
||||
evaluate_employee()
|
||||
# END OF CODE
|
||||
@@ -0,0 +1,94 @@
|
||||
# Assignment-C6 (Expert System - Stock Market Trading)
|
||||
|
||||
"""
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: Implement any one of the following Expert System
|
||||
V. Stock market trading
|
||||
|
||||
Code from ArtificialIntelligence (SPPU - Third Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-te-comp-content/ArtificialIntelligence
|
||||
"""
|
||||
|
||||
"""
|
||||
Install required package: experta
|
||||
pip install experta
|
||||
"""
|
||||
|
||||
# BEGINNING OF CODE
|
||||
from experta import *
|
||||
|
||||
# Define the Stock Fact
|
||||
class Stock(Fact):
|
||||
"""Stock details"""
|
||||
name: str
|
||||
current_price: float
|
||||
pe_ratio: float
|
||||
volatility: str # high, medium, low
|
||||
trend: str # bullish, bearish, sideways
|
||||
sector: str
|
||||
risk_tolerance: str # low, medium, high
|
||||
holding: bool # already holding the stock or not
|
||||
|
||||
# Expert System for Stock Trading
|
||||
class StockTradingAdvisor(KnowledgeEngine):
|
||||
|
||||
@Rule(Stock(trend='bullish', pe_ratio=P(lambda x: x < 25), volatility='low', risk_tolerance='low', holding=False))
|
||||
def buy_low_risk_stock(self):
|
||||
print("Advice: BUY the stock - Low-risk bullish opportunity with good valuation.")
|
||||
|
||||
@Rule(Stock(trend='bullish', pe_ratio=P(lambda x: x < 40), volatility='high', risk_tolerance='high', holding=False))
|
||||
def buy_aggressive_stock(self):
|
||||
print("Advice: BUY the stock - High potential for return, suitable for high-risk appetite.")
|
||||
|
||||
@Rule(Stock(trend='bearish', holding=True))
|
||||
def sell_on_downtrend(self):
|
||||
print("Advice: SELL the stock - Market is bearish and you're holding the stock.")
|
||||
|
||||
@Rule(Stock(trend='sideways', holding=True))
|
||||
def hold_in_uncertainty(self):
|
||||
print("Advice: HOLD the stock - No clear trend, wait for a signal.")
|
||||
|
||||
@Rule(Stock(trend='bullish', holding=True))
|
||||
def hold_during_bull_run(self):
|
||||
print("Advice: HOLD the stock - Already in a bullish trend, ride the wave.")
|
||||
|
||||
@Rule(Stock(pe_ratio=P(lambda x: x > 50), volatility='high', risk_tolerance='low'))
|
||||
def avoid_overvalued_stock(self):
|
||||
print("Advice: AVOID the stock - Highly volatile and overvalued, not suitable for low risk tolerance.")
|
||||
|
||||
@Rule(Stock(volatility='medium', trend='bullish', risk_tolerance='medium'))
|
||||
def moderate_buy(self):
|
||||
print("Advice: BUY the stock - Balanced risk and good growth potential.")
|
||||
|
||||
# Run function
|
||||
def run_trading_expert():
|
||||
engine = StockTradingAdvisor()
|
||||
engine.reset()
|
||||
|
||||
print("\n--- Enter Stock Details ---")
|
||||
name = input("Stock Name: ")
|
||||
current_price = float(input("Current Price: "))
|
||||
pe_ratio = float(input("P/E Ratio: "))
|
||||
volatility = input("Volatility (low/medium/high): ").lower()
|
||||
trend = input("Market Trend (bullish/bearish/sideways): ").lower()
|
||||
sector = input("Sector: ")
|
||||
risk_tolerance = input("Your Risk Tolerance (low/medium/high): ").lower()
|
||||
holding = input("Are you currently holding this stock? (yes/no): ").lower() == "yes"
|
||||
|
||||
engine.declare(Stock(
|
||||
name=name,
|
||||
current_price=current_price,
|
||||
pe_ratio=pe_ratio,
|
||||
volatility=volatility,
|
||||
trend=trend,
|
||||
sector=sector,
|
||||
risk_tolerance=risk_tolerance,
|
||||
holding=holding
|
||||
))
|
||||
|
||||
print("\n🔍 Analyzing Market Conditions...\n")
|
||||
engine.run()
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_trading_expert()
|
||||
# END OF CODE
|
||||
Reference in New Issue
Block a user