diff --git a/Codes/Alternatives/Assignment-A1.py b/Codes/Alternatives/Assignment-A1.py new file mode 100644 index 0000000..5932648 --- /dev/null +++ b/Codes/Alternatives/Assignment-A1.py @@ -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 diff --git a/Codes/Alternatives/Assignment-A2-Direct.py b/Codes/Alternatives/Assignment-A2-Direct.py new file mode 100644 index 0000000..941ca64 --- /dev/null +++ b/Codes/Alternatives/Assignment-A2-Direct.py @@ -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 diff --git a/Codes/Alternatives/Assignment-A2-Maze.py b/Codes/Alternatives/Assignment-A2-Maze.py new file mode 100644 index 0000000..aa6e5c6 --- /dev/null +++ b/Codes/Alternatives/Assignment-A2-Maze.py @@ -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)] +""" diff --git a/Codes/Alternatives/Assignment-A3-2.py b/Codes/Alternatives/Assignment-A3-2.py new file mode 100644 index 0000000..1ce7e54 --- /dev/null +++ b/Codes/Alternatives/Assignment-A3-2.py @@ -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 diff --git a/Codes/Alternatives/Assignment-A3.V.py b/Codes/Alternatives/Assignment-A3.V.py new file mode 100644 index 0000000..9716a98 --- /dev/null +++ b/Codes/Alternatives/Assignment-A3.V.py @@ -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 diff --git a/Codes/Alternatives/Assignment-B5.py b/Codes/Alternatives/Assignment-B5.py new file mode 100644 index 0000000..b4dcb26 --- /dev/null +++ b/Codes/Alternatives/Assignment-B5.py @@ -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 diff --git a/Codes/Alternatives/Assignment-C6-Airline.py b/Codes/Alternatives/Assignment-C6-Airline.py new file mode 100644 index 0000000..c4777ad --- /dev/null +++ b/Codes/Alternatives/Assignment-C6-Airline.py @@ -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 diff --git a/Codes/Alternatives/Assignment-C6-Employee.py b/Codes/Alternatives/Assignment-C6-Employee.py new file mode 100644 index 0000000..ce16444 --- /dev/null +++ b/Codes/Alternatives/Assignment-C6-Employee.py @@ -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 diff --git a/Codes/Alternatives/Assignment-C6-Stock.py b/Codes/Alternatives/Assignment-C6-Stock.py new file mode 100644 index 0000000..9e44a83 --- /dev/null +++ b/Codes/Alternatives/Assignment-C6-Stock.py @@ -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 diff --git a/Codes/Assignment-A1.py b/Codes/Assignment-A1.py new file mode 100644 index 0000000..6d87de7 --- /dev/null +++ b/Codes/Assignment-A1.py @@ -0,0 +1,96 @@ +# Assignment-A1: DFS & BFS + +""" +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 +""" + +# BEGINNING OF CODE +from collections import deque + +class Graph: + # Constructor to initalize an empty dictionary + def __init__(self): + self.graph = {} + + # Add edges + def add_edge(self, u, v): + if u not in self.graph: + self.graph[u] = [] + if v not in self.graph: + self.graph[v] = [] + self.graph[u].append(v) + self.graph[v].append(u) # Since the graph is undirected; Comment this line if graph is directed. + + # Perform Depth First Search (DFS) + def dfs(self, start, visited=None): + if visited is None: + visited = set() + + visited.add(start) + print(start, end=" ") + + for neighbour in self.graph.get(start, []): + if neighbour not in visited: + self.dfs(neighbour, visited) + + # Perform Breadth First Search (BFS) + def bfs(self, start): + visited = set() + visited.add(start) + queue = deque([start]) + + def bfs_helper(): + if not queue: + return + + vertex = queue.popleft() + print(vertex, end=" ") + + for neighbour in self.graph.get(vertex, []): + if neighbour not in visited: + visited.add(neighbour) + queue.append(neighbour) + bfs_helper() + + bfs_helper() + +def main(): + g = Graph() + + while True: + print("\n\n", "-"*10, "MAIN MENU", "-"*10) + print("1. Add edge") + print("2. Depth First Search (DFS)") + print("3. Breadth First Search (BFS)") + print("4. Exit") + choice = int(input("Choose an option (1-4):\t")) + print("-"*32) + + if choice == 1: + total = int(input("\nTotal edges to add:\t")) + for i in range(total): + print(f"EDGE {i+1} ->") + u = input(f"Enter first vertex for edge {i+1}: ") + v = input(f"Enter second vertex for edge {i+1}: ") + g.add_edge(u, v) + print("\nVertices and its neighbours are:\t", g.graph) + elif choice == 2: + start = input("\nEnter starting vertex for DFS:\t") + print("Depth First Search (DFS):\t") + g.dfs(start) + elif choice == 3: + start = input("\nEnter starting vertex for BFS:\t") + print("Breadth First Search (BFS):\t") + g.bfs(start) + elif choice == 4: + print("\n## END OF CODE\n") + break + else: + print("\nPlease choose a valid option.") + +main() +# END OF CODE diff --git a/Codes/Assignment-A2.py b/Codes/Assignment-A2.py new file mode 100644 index 0000000..b15b1c2 --- /dev/null +++ b/Codes/Assignment-A2.py @@ -0,0 +1,143 @@ +# Assignment-A2 (A* for 8 Puzzle Problem) + +""" +THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL. + +Problem Statement: Problem Statement: Implement A star Algorithm for 8 puzzle 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 8 puzzle problem since the problem +# statement in our syllabus and handout demands implementing A* algorithm +# for any game search problem. + +# A* implementation for maze problem and direct implementation can be found +# in the "Alternatives" folder. + + +# Enter the initial state as 9 numbers (0 represents the blank tile): +# Enter row 1 (3 numbers separated by spaces): 1 2 3 +# Enter row 2 (3 numbers separated by spaces): 0 4 6 +# Enter row 3 (3 numbers separated by spaces): 7 5 8 + +# BEGINNING OF CODE +import heapq + +goal_state = [[1, 2, 3], + [4, 5, 6], + [7, 8, 0]] + +# Directions for moving the blank tile +directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] # up, down, left, right + +def h_misplaced_tiles(state): + misplaced = 0 + for i in range(3): + for j in range(3): + if state[i][j] != 0 and state[i][j] != goal_state[i][j]: + misplaced += 1 + return misplaced + +def find_blank(state): + for i in range(3): + for j in range(3): + if state[i][j] == 0: + return i, j + +def is_valid(x, y): + return 0 <= x < 3 and 0 <= y < 3 + +def state_to_tuple(state): + return tuple(tuple(row) for row in state) + +def a_star(start_state): + start = state_to_tuple(start_state) + g = 0 + h = h_misplaced_tiles(start_state) + f = g + h + + # Priority queue with elements: (f, g, state, path) + pq = [(f, g, start_state, [])] + visited = set() + + while pq: + f, g, current, path = heapq.heappop(pq) + current_tuple = state_to_tuple(current) + + if current_tuple in visited: + continue + visited.add(current_tuple) + + if current == goal_state: + return path + [current] + + x, y = find_blank(current) + + for dx, dy in directions: + nx, ny = x + dx, y + dy + if is_valid(nx, ny): + # Create new state by swapping blank + new_state = [row[:] for row in current] + new_state[x][y], new_state[nx][ny] = new_state[nx][ny], new_state[x][y] + + if state_to_tuple(new_state) not in visited: + new_g = g + 1 + new_h = h_misplaced_tiles(new_state) + new_f = new_g + new_h + heapq.heappush(pq, (new_f, new_g, new_state, path + [current])) + + return None + +def print_path(path): + for step, state in enumerate(path): + print(f"Step {step}:") + for row in state: + print(row) + print() + +def get_input_state(): + print("Enter the initial state as 9 numbers (0 represents the blank tile):") + state = [] + for i in range(3): + row = input(f"Enter row {i+1} (3 numbers separated by spaces): ").split() + state.append([int(num) for num in row]) + return state + +initial_state = get_input_state() + +solution_path = a_star(initial_state) + +if solution_path: + print_path(solution_path) +else: + print("No solution found.") +# END OF CODE + +""" +SAMPLE OUTPUT + +Enter the initial state as 9 numbers (0 represents the blank tile): +Enter row 1 (3 numbers separated by spaces): 1 2 3 +Enter row 2 (3 numbers separated by spaces): 0 4 6 +Enter row 3 (3 numbers separated by spaces): 7 5 8 +Step 0: +[1, 2, 3] +[0, 4, 6] +[7, 5, 8] + +Step 1: +[1, 2, 3] +[4, 0, 6] +[7, 5, 8] + +Step 2: +[1, 2, 3] +[4, 5, 6] +[7, 0, 8] + +Step 3: +[1, 2, 3] +[4, 5, 6] +[7, 8, 0] +""" diff --git a/Codes/Assignment-A3.I.py b/Codes/Assignment-A3.I.py new file mode 100644 index 0000000..7585f69 --- /dev/null +++ b/Codes/Assignment-A3.I.py @@ -0,0 +1,57 @@ +# Assignment-A3.I (Selection Sort) + +""" +THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL. + +Problem Statement: Implement Greedy search algorithm for any of the following application: + I. Selection Sort + +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 = [] # Empty list to store numbers + +# Function to take input for numbers +def input_numbers(): + total = int(input("\nHow many numbers you wish to enter?\nTotal numbers:\t")) + for i in range(total): + val = float(input(f"Enter number {i+1}:\t")) + numbers.append(val) + print("Numbers you've entered are:\t", numbers) + +# Function for selection sort +def selection_sort(): + for i in range(len(numbers)): + min_index = i + for j in range(i+1, len(numbers)): + if numbers[j] < numbers[min_index]: + min_index = j + numbers[i], numbers[min_index] = numbers[min_index], numbers[i] # Swapping + print("\nNumbers sorted in ascending order using selection sort:\t", numbers) + +# Main function for menu +def main(): + while True: + print("\n\n", "-"*10, "MAIN MENU", "-"*10) + print("1. Enter numbers") + print("2. Apply selection sort") + print("3. List numbers") + print("4. Exit") + choice = int(input("Choose an option (1-4):\t")) + print("-"*32) + + if (choice == 1): + input_numbers() + elif (choice == 2): + selection_sort() + elif (choice == 3): + print("\nNumbers you've entered are:\t", numbers) + elif (choice == 4): + print("\n## END OF CODE\n") + break + else: + print("\nPlease choose a valid option (1-4)") + +main() +# END OF CODE diff --git a/Codes/Assignment-A3.IV.py b/Codes/Assignment-A3.IV.py new file mode 100644 index 0000000..1e47b05 --- /dev/null +++ b/Codes/Assignment-A3.IV.py @@ -0,0 +1,51 @@ +# Assignment-A3.IV (Job Scheduling) + +""" +THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL. + +Problem Statement: Implement Greedy search algorithm for any of the following application: + IV. Job Scheduling Problem + +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 job_scheduling(): + jobs = [] + total = int(input("Total jobs to add:\t")) + + # Take input for jobs + print("\n", "-"*10, "JOBS", "-"*10, "\n") + for i in range(total): + print(f"JOB {i+1} ->") + job_id = int(input(f"ID for job {i+1}:\t\t")) + deadline = int(input(f"Deadline for job {i+1}:\t")) + profit = int(input(f"Profit for job {i+1}:\t")) + jobs.append((job_id, deadline, profit)) # Index 0 for job_id; Index 1 for deadline; Index 2 for profit + print(f"\nAdded {total} jobs.") + print("-"*27, "\n") + + # Initialize + jobs.sort(key=lambda x: x[2], reverse=True) # Sort jobs by profit; Using index 2 to access profit + max_deadline = max(job[1] for job in jobs) # Highest deadline; Using index 1 to access deadline + slots = [0] * (max_deadline + 1) + total_profit = 0 + + # Scheduling jobs using greedy strategy + for job in jobs: + for i in range(job[1], 0, -1): + if slots[i] == 0: + slots[i] = job[0] + total_profit += job[2] + break + + # Print scheduled jobs + print("Scheduled Jobs:", end=" ") + for i in range(1, len(slots)): + if slots[i] != 0: + print(slots[i], end=" ") + + print(f"\nTotal Profit: {total_profit}\n") + +job_scheduling() +# END OF CODE diff --git a/Codes/Assignment-A3.py b/Codes/Assignment-A3.py new file mode 100644 index 0000000..f337551 --- /dev/null +++ b/Codes/Assignment-A3.py @@ -0,0 +1,98 @@ +# Assignment-A3 + +""" +THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL. + +Problem Statement: Implement Greedy search algorithm for any of the following application: + I. Selection Sort + IV. Job Scheduling Problem + +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 +# BEGINNING OF SELECTION SORT +numbers = [] # Empty list to store numbers + +# Function to take input for numbers +def input_numbers(): + total = int(input("\nHow many numbers you wish to enter?\nTotal numbers:\t")) + for i in range(total): + val = float(input(f"Enter number {i+1}:\t")) + numbers.append(val) + print("\nNumbers you've entered are:\t", numbers) + +# Function for selection sort +def selection_sort(): + for i in range(len(numbers)): + min_index = i + for j in range(i+1, len(numbers)): + if numbers[j] < numbers[min_index]: + min_index = j + numbers[i], numbers[min_index] = numbers[min_index], numbers[i] # Swapping + print("Numbers sorted in ascending order using selection sort:\t", numbers) +# END OF SELECTION SORT + +# BEGINNING OF JOB SCHEDULING +def job_scheduling(): + jobs = [] + total = int(input("Total jobs to add:\t")) + + # Take input for jobs + print("\n", "-"*10, "JOBS", "-"*10, "\n") + for i in range(total): + print(f"JOB {i+1} ->") + job_id = int(input(f"ID for job {i+1}:\t\t")) + deadline = int(input(f"Deadline for job {i+1}:\t")) + profit = int(input(f"Profit for job {i+1}:\t")) + jobs.append((job_id, deadline, profit)) # Index 0 for job_id; Index 1 for deadline; Index 2 for profit + print(f"\nAdded {total} jobs.") + print("-"*27, "\n") + + # Initialize + jobs.sort(key=lambda x: x[2], reverse=True) # Sort jobs by profit; Using index 2 to access profit + max_deadline = max(job[1] for job in jobs) # Highest deadline; Using index 1 to access deadline + slots = [0] * (max_deadline + 1) + total_profit = 0 + + # Scheduling jobs using greedy strategy + for job in jobs: + for i in range(job[1], 0, -1): + if slots[i] == 0: + slots[i] = job[0] + total_profit += job[2] + break + + # Print scheduled jobs + print("Scheduled Jobs:", end=" ") + for i in range(1, len(slots)): + if slots[i] != 0: + print(slots[i], end=" ") + + print(f"\nTotal Profit: {total_profit}") +# END OF JOB SCHEDULING + + +# Main function for menu +def main(): + while True: + print("\n\n", "-"*10, "MAIN MENU", "-"*10) + print("1. Selection Sort") + print("2. Job Scheduling") + print("3. Exit") + choice = int(input("Choose an option (1-3):\t")) + print("-"*32) + + if (choice == 1): + input_numbers() + selection_sort() + elif (choice == 2): + job_scheduling() + elif (choice == 3): + print("\n## END OF CODE\n") + break + else: + print("\nPlease choose a valid option (1-3)") + +main() +# END OF CODE diff --git a/Codes/Assignment-B4.py b/Codes/Assignment-B4.py new file mode 100644 index 0000000..d5947c3 --- /dev/null +++ b/Codes/Assignment-B4.py @@ -0,0 +1,61 @@ +# Assignment-B4 (N-Queen) + +""" +THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL. + +Problem Statement: Implement a solution for a Constraint Satisfaction Problem using Branch and Bound and Backtracking for n-queens problem or a graph coloring problem. + +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 placeQueens(i, cols, leftDiagonal, rightDiagonal, cur): + n = len(cols) + + if i == n: + return True + + for j in range(n): + if cols[j] or rightDiagonal[i + j] or leftDiagonal[i - j + n - 1]: + continue + + cols[j] = 1 + rightDiagonal[i + j] = 1 + leftDiagonal[i - j + n - 1] = 1 + cur.append(j) + + if placeQueens(i + 1, cols, leftDiagonal, rightDiagonal, cur): + return True + + cur.pop() + cols[j] = 0 + rightDiagonal[i + j] = 0 + leftDiagonal[i - j + n - 1] = 0 + + return False + +def nQueen(n): + cols = [0] * n + leftDiagonal = [0] * (n * 2) + rightDiagonal = [0] * (n * 2) + cur = [] + board = [['.' for _ in range(n)] for _ in range(n)] + + if placeQueens(0, cols, leftDiagonal, rightDiagonal, cur): + for i in range(n): + board[i][cur[i]] = 'Q' + return board + else: + return None + +def printBoard(board): + if board: + for row in board: + print(" ".join(row)) + else: + print("No solution exists.") + +n = int(input("Enter the number of queens:\t")) +board = nQueen(n) +printBoard(board) +# END OF CODE diff --git a/Codes/Assignment-B5.py b/Codes/Assignment-B5.py new file mode 100644 index 0000000..f034ce3 --- /dev/null +++ b/Codes/Assignment-B5.py @@ -0,0 +1,54 @@ +# 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 datetime + +def restaurant_chatbot(): + print("Welcome to the K's Restaurant!") + print("You can ask me about the menu, cost, contact details or reservations!") + + while True: + user_input = input("\nYou: ").lower() + + if "menu" in user_input: + print("Chatbot: Our menu includes pasta, pizza, salads, and desserts.") + + elif "cost" in user_input or "price" in user_input or "how much" in user_input: + print("Chatbot: The average cost per person is around $20.") + + elif "contact" in user_input or "phone" in user_input: + print("Chatbot: You can contact us at +91-1234567890") + + elif "reservation" in user_input or "book" in user_input: + print("Chatbot: To make a reservation, please call us at +91-1234567890 or visit our website at https://k-rest.io") + + elif "hours" in user_input: + print("Chatbot: We are open from 11 AM to 10 PM, Monday to Sunday.") + + elif "date" in user_input or "time" in user_input: + now = datetime.datetime.now() + print(f"Chatbot: Today's date and time is {now.strftime('%Y-%m-%d %H:%M:%S')}.") + + elif "how are you" in user_input or "how's it going" in user_input or "sup" in user_input: + print("Chatbot: I'm just a bot, but I'm here to help you! How can I assist you today?") + + elif "meow" in user_input: + print("Meow meow meow!") + + elif "exit" in user_input or "quit" in user_input: + print("Chatbot: Thank you for chatting with us! Have a great day!") + break + + else: + print("Chatbot: I'm sorry, I didn't understand that. Can you ask something else?") + +restaurant_chatbot() +# END OF CODE diff --git a/Codes/Assignment-C6.py b/Codes/Assignment-C6.py new file mode 100644 index 0000000..e0a8419 --- /dev/null +++ b/Codes/Assignment-C6.py @@ -0,0 +1,59 @@ +# Assignment-C6 (Expert System - Hospitals and Medical Facilities) + +""" +THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL. + +Problem Statement: Implement any one of the following Expert System + II. Hospitals and medical facilities + +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 knowledge(): + return { + "sneezes":"Cold", + "temperature":"Fever", + "weakness": "Iron Deficiency", + "forgets":"Alzeimers", + "cough":"Covid-19", + "paleness":"Flu" + } + +def ask(q): + while True: + a= input(f"{q} [Yes/No]\t").lower() + if a in ['yes', 'no']: + if a== "yes": return True + return False + else: print("Please Answer in Yes or No.\n") + +def questions_List(): + return { + "sneezes": "Are you sneezing frequently?", + "temperature": "Do you have high temperature?", + "weakness": "Are you feeling weak in your legs and arms?", + "forgets": "Are you able to remember things clearly?", + "cough": "Do you have cough or sore throat?", + "paleness": "Does your skin look pale?", + } + +# P.S. The author wants the user to notice the subtle use of questions.items() to retrieve the entire key value pair from the dictionary. + +def doctor(): + print("*"*30,"\nWelcome to Doctor Smith's!","*"*30) + know=knowledge() + questions=questions_List() + symtoms={} + for s,q in questions.items(): + symtoms[s]=ask(q) + diagnosis=[] + for sym in know: + if symtoms[sym]: + diagnosis.append(know[sym]) + print("\n\nYour Diagnosis is: \n") + for d in diagnosis: + print(d) + +doctor() +# END OF CODE