pdf24 Merged
pdf24 Merged
PROGRAM
import random
def input_graph(n):
graph = []
print("Enter the weights between nodes (use 0 if not connected):")
for i in range(n):
row = []
for j in range(n):
if i == j:
row.append(0)
elif j < i:
row.append(graph[j][i]) # Copy the upper triangle to lower
else:
value = int(input(f"Is {i} connected to {j}? "))
row.append(value)
graph.append(row)
return graph
def hill_climbing(graph):
n = len(graph)
current_path = []
for i in range(n):
current_path.append(i)
random.shuffle(current_path)
if i != j:
neighbor = []
for item in current_path:
neighbor.append(item)
temp = neighbor[i]
neighbor[i] = neighbor[j]
neighbor[j] = temp
graph = input_graph(n)
print("Adjacency Matrix:")
for i in range(n):
for j in range(n):
print(graph[i][j], end=' ')
print()
PROGRAM
import heapq
class Cell:
def __init__(self, parent_i, parent_j):
self.parent_i = parent_i
self.parent_j = parent_j
self.f = 0.0
self.g = 0.0
self.h = 0.0
ROW = 9
COL = 10
path.append((row, col))
path.reverse()
print("Path found:")
for i in range(len(path)):
print(path[i], end="")
if i != len(path) - 1:
print(" -> ", end="")
print()
closed_list = []
for i in range(ROW):
closed_list.append([False] * COL)
cell_details = []
for i in range(ROW):
row = []
for j in range(COL):
row.append(Cell(-1, -1))
cell_details.append(row)
i = src[0]
j = src[1]
cell_details[i][j].f = 0.0
cell_details[i][j].g = 0.0
cell_details[i][j].h = 0.0
cell_details[i][j].parent_i = i
cell_details[i][j].parent_j = j
open_list = []
heapq.heappush(open_list, (0.0, (i, j)))
found_dest = False
closed_list[i][j] = True
for d in directions:
new_i = i + d[0]
new_j = j + d[1]
if is_valid(new_i, new_j):
if is_destination(new_i, new_j, dest):
cell_details[new_i][new_j].parent_i = i
cell_details[new_i][new_j].parent_j = j
trace_path(cell_details, dest)
found_dest = True
return
if not found_dest:
print("No path found to destination")
grid = [
[1, 0, 1, 1, 1, 1, 0, 1, 1, 1],
[1, 1, 1, 0, 1, 1, 1, 0, 1, 1],
[1, 1, 1, 0, 1, 1, 0, 1, 0, 1],
[0, 0, 1, 0, 1, 0, 0, 0, 0, 1],
[1, 1, 1, 0, 1, 1, 1, 0, 1, 0],
[1, 0, 1, 1, 1, 1, 0, 1, 0, 0],
[1, 0, 0, 0, 0, 1, 0, 0, 0, 1],
[2, 0, 1, 1, 1, 1, 0, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 1, 0, 0, 1]
]
src = (8, 0)
dest = (0, 0)
PROGRAM
import math
def print_board(board):
print("\n")
for i in range(0, 9, 3):
print(" | ".join(board[i:i+3]))
if i < 6:
print("-" * 9)
print("\n")
def check_winner(board):
win_states = [
[board[0], board[1], board[2]],
[board[3], board[4], board[5]],
[board[6], board[7], board[8]],
[board[0], board[3], board[6]],
[board[1], board[4], board[7]],
[board[2], board[5], board[8]],
[board[0], board[4], board[8]],
[board[2], board[4], board[6]],
]
if ["X", "X", "X"] in win_states:
return 1
elif ["O", "O", "O"] in win_states:
return -1
elif " " not in board:
return 0
return None
def find_best_move(board):
best_move = None
best_score = -math.inf
for i in range(9):
if board[i] == " ":
board[i] = "X"
score = minimax(board, 0, False)
board[i] = " "
if score > best_score:
best_score = score
best_move = i
return best_move
def play_game():
board = [" "] * 9
print("Welcome to Tic-Tac-Toe! AI (X) vs You (O)")
print_board(board)
while True:
user_move = int(input("Enter your move (0-8): "))
if board[user_move] != " ":
print("Invalid move! Try again.")
continue
board[user_move] = "O"
print_board(board)
if check_winner(board) == -1:
print("You win! ")
break
elif check_winner(board) == 0:
print("It's a draw! ")
break
print("AI is thinking...")
ai_move = find_best_move(board)
board[ai_move] = "X"
print_board(board)
if check_winner(board) == 1:
print("AI wins! ")
break
elif check_winner(board) == 0:
print("It's a draw! ")
break
play_game()
OUTPUT
ADVERSARIAL SEARCH [SNAKE & LADDER]
PROGRAM
import random
import time
snakes = {
16: 6,
47: 26,
49: 11,
56: 53,
62: 19,
64: 60,
87: 24,
93: 73,
95: 75,
98: 78
}
ladders = {
1: 38,
4: 14,
9: 31,
21: 42,
28: 84,
36: 44,
51: 67,
71: 91,
80: 100
}
def roll_dice():
return random.randint(1, 6)
def move_player(position):
if position in snakes:
print("Oops! Bitten by a snake ")
return snakes[position]
elif position in ladders:
print("Yay! Climbed a ladder ")
return ladders[position]
return position
def play_game():
human_pos = 0
ai_pos = 0
while True:
input(" Your turn! Press Enter to roll the dice...")
dice = roll_dice()
print("You rolled:", dice)
human_pos += dice
if human_pos > 100:
human_pos -= dice
print("You need exactly", 100 - human_pos, "to win.")
else:
human_pos = move_player(human_pos)
if human_pos == 100:
print("Congratulations! You won!")
break
time.sleep(1)
if ai_pos == 100:
print(" AI wins! Better luck next time!")
break
print("-" * 40)
time.sleep(1)
if __name__ == "__main__":
play_game()
OUTPUT
ADVERSARIAL SEARCH [ROCK, PAPER & SCISSOR]
PROGRAM
import random
def play_rps():
choices = ["rock", "paper", "scissors"]
while True:
print("******************************************************")
player_choice = input("Enter rock, paper, or scissors (or 'quit' to stop): ").lower()
if player_choice == "quit":
break
elif player_choice not in choices:
print("Invalid choice! Try again.")
continue
ai_choice = random.choice(choices)
print(f"AI chose: {ai_choice}")
print("******************************************************")
play_rps()
OUTPUT
FIRST ORDER LOGIC
PROGRAM
valuable(gold).
female(jane).
owns(jane, gold).
father(john, mary).
likes(john, flowers).
likes(john, apples).
likes(john, mangoes).
likes(john, mary).
likes(john, burger).
likes(john, pizza).
likes(john, snow).
likes(john, dollar).
hates(john, orange).
dislikes(john, banana).
likes(mary, chocolate).
likes(mary, burger).
likes(mary, pizza).
thief(wini).
thief(john).
thief(william).
likes(wini, ball).
likes(william, shoe).
?- valuable(gold).
true.
?- valuable(salt).
false.
?- father(john, mary).
true.
?- female(jane).
true.
?- likes(john, X).
?- hates(john, Y).
Y = orange.
?- dislikes(john, Z).
Z = banana.
X = burger ; X = pizza.
?- may_steal(john, A).
?- may_steal(john, jewellery).
false.
?- may_steal(john, ball).
false.
?- may_steal(john, snow).
true.
N-QUEENS PROBLEM
PROGRAM
return True
res = False
for i in range(N):
if is_safe(board, i, col, N):
board[i][col] = 1
if solve_n_queens(board, col + 1, N, last_solution):
res = True
board[i][col] = 0
return res
def solve(N):
board = [[0 for _ in range(N)] for _ in range(N)]
last_solution = []
PROGRAM
def get_distance_matrix(cities):
n = len(cities)
dist = [[0] * n for _ in range(n)]
def main():
print("=== Travelling Salesman Problem ===")
num = int(input("Enter number of cities: "))
cities = []
for i in range(num):
name = input(f"Enter name for city {i + 1}: ")
cities.append(name)
dist_matrix = get_distance_matrix(cities)
if __name__ == "__main__":
main()
OUTPUT
MULTI AGENT SYSTEM [MAZE]
PROGRAM
import tkinter as tk
from tkinter import messagebox
CELL_SIZE = 50
ROWS = len(MAZE)
COLS = len(MAZE[0])
START = (1, 1)
END = (8, 7)
class MazeGame:
def __init__(self, root):
self.root = root
self.root.title("Maze Game")
self.canvas = tk.Canvas(root, width=COLS * CELL_SIZE, height=ROWS *
CELL_SIZE)
self.canvas.pack()
self.player_pos = START
self.draw_maze()
self.draw_player()
root.bind("<Key>", self.move_player)
def draw_maze(self):
for r in range(ROWS):
for c in range(COLS):
x1 = c * CELL_SIZE
y1 = r * CELL_SIZE
x2 = x1 + CELL_SIZE
y2 = y1 + CELL_SIZE
if MAZE[r][c] == 1:
self.canvas.create_rectangle(x1, y1, x2, y2, fill="black")
else:
self.canvas.create_rectangle(x1, y1, x2, y2, fill="white", outline="gray")
gx, gy = END
self.canvas.create_rectangle(
gy * CELL_SIZE, gx * CELL_SIZE,
(gy + 1) * CELL_SIZE, (gx + 1) * CELL_SIZE,
fill="green"
)
def draw_player(self):
r, c = self.player_pos
x1 = c * CELL_SIZE + 10
y1 = r * CELL_SIZE + 10
x2 = x1 + CELL_SIZE - 20
y2 = y1 + CELL_SIZE - 20
self.player = self.canvas.create_oval(x1, y1, x2, y2, fill="blue", tags="player")
if 0 <= new_r < ROWS and 0 <= new_c < COLS and MAZE[new_r][new_c] == 0:
self.player_pos = (new_r, new_c)
self.canvas.move("player", (new_c - c) * CELL_SIZE, (new_r - r) * CELL_SIZE)
if self.player_pos == END:
messagebox.showinfo("Maze Game", " You reached the goal!")
self.root.quit()
if __name__ == "__main__":
root = tk.Tk()
game = MazeGame(root)
root.mainloop()
OUTPUT
Aim:
To develop an AI-powered chatbot, FinBot, that assists users in making informed financial
decisions by providing personalized guidance on budgeting, saving, investing, credit
management, debt repayment, and retirement planning, tailored to various user roles such as
investors, savers, borrowers, and financial planners.
Description:
FinBot is a comprehensive AI-powered chatbot integrated into a personal finance application,
designed to support users in managing their finances and making informed financial choices.
Developed using cutting-edge technologies like Natural Language Processing (NLP), machine
learning, and contextual AI models (e.g., Rasa, ChatGPT API), FinBot provides round-the-clock
support to users involved in various aspects of personal finance.
The core purpose of FinBot is to bridge the communication and knowledge gap between
individuals and financial services by offering instant, personalized assistance. By
understanding the user's intent and context, FinBot delivers intelligent responses and
actionable financial advice.
1. Investor:
FinBot helps users evaluate investment opportunities, offers tips on diversifying
portfolios, explains stock market basics, and provides market insights. It assists with
selecting ETFs, index funds, and understanding risk levels, all while encouraging smart,
long-term investment strategies.
2. Saver:
FinBot provides personalized saving tips, helps users set financial goals, and advises on
emergency funds. It offers methods to automate savings, track spending, and identify
areas for potential savings, ensuring that users are always on track to meet their
financial objectives.
3. Borrower:
Borrowers can use FinBot to understand different loan types (e.g., personal, mortgage,
student loans), compare interest rates, and explore repayment strategies. The bot also
provides tips on improving credit scores and avoiding high-interest debt, ensuring
borrowers make sound financial decisions.
4. Financial Planner:
FinBot assists financial planners in creating long-term financial strategies for their
clients. It offers tools for retirement planning, tax filing advice, and estate planning,
helping planners optimize financial portfolios for future security.
5. Credit: Manager:
FinBot helps users manage credit, offering advice on improving credit scores,
understanding credit reports, and managing credit card usage. It also provides
guidance on utilizing credit responsibly to maintain financial health and avoid falling
into debt.
Universal Features:
In addition to role-specific support, FinBot includes universal features accessible by all users:
Technology Stack:
• OpenAI GPT API for dynamic financial guidance (e.g., budgeting advice, investment
tips)
• Geo APIs for location-based financial assistance (e.g., finding financial advisors)
Impact:
FinBot supports SDG 1 (No Poverty) and SDG 8 (Decent Work and Economic Growth) by
enhancing financial literacy and empowering users to manage their finances. It helps users
achieve financial independence, reduce debt, and plan for retirement, fostering financial
stability and contributing to sustainable economic growth.
PROGRAM CODE:
import random
import re
import json
import os
app = Flask(__name__)
knowledge_base = {
"greetings": [
"Hello! I'm FinBot, your personal financial assistant. How can I help you today?",
"Welcome! I'm FinBot. Whether it's budgeting or investing, I've got you covered."
],
"farewells": [
],
"thanks": [
],
"identity": [
"I'm FinBot, your smart assistant for all things personal finance — budgeting, investing,
saving, and more!",
"FinBot here! I help you understand and improve your financial life.",
],
"budgeting_tips": [
"A 50/30/20 budget rule is a great starting point: 50% needs, 30% wants, 20% savings.",
"Tracking every expense for a month can uncover surprising spending habits.",
],
"emergency_fund": [
"Keep your emergency fund in a high-yield savings account for easy access and growth.",
"Unexpected events happen — your emergency fund gives you peace of mind."
],
"saving_tips": [
"Cut small daily costs like takeout coffee to save more over time."
],
"investment_basics": [
"Investing means putting your money to work for potential future returns.",
"Start with index funds or ETFs — they offer diversification and lower risk.",
"Only invest money you can leave untouched for at least 5 years."
],
"stock_vs_bonds": [
"Stocks are ownership in companies; bonds are loans you give to governments or
corporations.",
"Stocks are higher risk, higher reward. Bonds are more stable but usually lower returns."
],
"mutual_funds": [
"They are managed by professionals and are a great way to diversify easily."
],
"credit_score_basics": [
"A credit score reflects how reliably you manage debt. Higher scores mean better rates.",
"Pay bills on time, keep credit utilization low, and limit hard inquiries to improve your score."
],
"loan_types": [
"Each loan type has its own interest rates, term lengths, and approval criteria."
],
"debt_repayment_strategies": [
"Snowball method: pay smallest debts first. Avalanche method: pay highest interest first.",
"Always pay more than the minimum if you can to reduce interest."
],
"tax_filing_tips": [
"File your taxes early to avoid stress and reduce identity theft risks.",
"Keep all income and expense records organized throughout the year.",
],
"insurance_basics": [
"Insurance protects you from big financial losses — health, auto, home, and life are key
types.",
],
"retirement_planning": [
"Start retirement savings early to benefit from compound growth.",
"401(k)s and IRAs are great retirement vehicles with tax advantages.",
],
"compound_interest": [
"Compound interest means you earn interest on your interest. It’s the key to growing
wealth.",
"The earlier you start saving, the more time compounding works in your favor."
],
"financial_goals": [
],
"student_loans": [
"Know the difference between federal and private loans — repayment options differ.",
],
"credit_card_tips": [
"Pay off your credit card balance in full each month to avoid interest.",
"Use less than 30% of your credit limit to maintain a good credit score."
],
"mortgage_tips": [
"A fixed-rate mortgage offers predictable payments. An ARM may be cheaper short-term.",
],
"fraud_prevention": [
"financial_literacy": [
"Financial literacy means understanding how to manage money, debt, and investments
wisely.",
"Improving your financial knowledge leads to better decisions and financial freedom."
],
"unknown": [
"Hmm, I didn't quite catch that. Could you ask about savings, budgeting, or investing?",
"I'm still learning. Could you rephrase or try a finance-related topic like loans or
retirement?",
"Let’s stay on money matters. Ask me about credit, savings, debt, or financial planning!"
],
"learned_responses": []
def preprocess_text(text):
text = text.lower().strip()
return text
if os.path.exists('ecobot_knowledge_base.json'):
knowledge_base = json.load(f)
else:
json.dump(knowledge_base, f, indent=4)
user_info = {
"current_role": "unknown",
"waste_type": None
def detect_intent(user_input):
user_input = preprocess_text(user_input)
print(user_input)
# Basic interactions
if re.search(r'\b(hi|hello|hey|greetings)\b', user_input):
return "greetings"
return "farewells"
return "thanks"
return "identity"
return "emergency_fund"
return "saving_tips"
return "investment_basics"
return "stock_vs_bonds"
return "mutual_funds"
return "credit_score_basics"
return "loan_types"
return "debt_repayment_strategies"
return "tax_filing_tips"
return "insurance_basics"
return "retirement_planning"
return "compound_interest"
return "financial_goals"
elif re.search(r'\b(student loan|college debt|education loan)\b', user_input):
return "student_loans"
return "credit_card_tips"
return "mortgage_tips"
return "fraud_prevention"
return "financial_literacy"
# Default fallback
return "unknown"
def generate_response(user_input):
intent = detect_intent(user_input)
print(intent)
if intent in knowledge_base:
reply = random.choice(knowledge_base[intent])
print(reply)
return reply
# Default response
return random.choice(knowledge_base["unknown"])
# Conversation context (simplified)
conversation_context = {
"learning_mode": False,
"question_to_learn": "",
"last_user_input": ""
def process_message(user_input):
global conversation_context
if conversation_context["learning_mode"]:
conversation_context["learning_mode"] = False
elif conversation_context["question_to_learn"]:
knowledge_base["learned_responses"][conversation_context["question_to_learn"]] =
user_input
json.dump(knowledge_base, f, indent=4)
conversation_context["learning_mode"] = False
conversation_context["question_to_learn"] = ""
return "Thank you for teaching me! I'll remember that for future sustainability
discussions."
conversation_context["last_user_input"] = user_input
response = generate_response(user_input)
if response == "I don't know the answer to that eco-question yet. Would you like to teach
me? (yes/no)":
conversation_context["learning_mode"] = True
return response
@app.route("/")
def home():
return render_template("index.html")
@app.route("/get_response", methods=["POST"])
def get_response():
user_input = request.json.get("message")
bot_reply = process_message(user_input)
if __name__ == "__main__":
app.run(debug=True)
SCREENSHOTS:
RESULT: