0% found this document useful (0 votes)
11 views51 pages

pdf24 Merged

The document contains multiple programs demonstrating various algorithms including Hill Climbing, A* Search, and Adversarial Search for games like Tic Tac Toe and Snake & Ladder. Each section provides code implementations along with explanations of the algorithms' functionalities, such as pathfinding and decision-making in games. Additionally, it includes examples of First Order Logic to represent knowledge and reasoning.

Uploaded by

venkat Mohan
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)
11 views51 pages

pdf24 Merged

The document contains multiple programs demonstrating various algorithms including Hill Climbing, A* Search, and Adversarial Search for games like Tic Tac Toe and Snake & Ladder. Each section provides code implementations along with explanations of the algorithms' functionalities, such as pathfinding and decision-making in games. Additionally, it includes examples of First Order Logic to represent knowledge and reasoning.

Uploaded by

venkat Mohan
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/ 51

HILL CLIMBING PROBLEM

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 calculate_cost(graph, path):


cost = 0
for i in range(len(path) - 1):
cost = cost + graph[path[i]][path[i + 1]]
cost = cost + graph[path[-1]][path[0]]
return cost

def hill_climbing(graph):
n = len(graph)

current_path = []
for i in range(n):
current_path.append(i)

random.shuffle(current_path)

current_cost = calculate_cost(graph, current_path)

print("Initial path:", current_path)


print("Initial cost:", current_cost)
for _ in range(1000):
i = random.randint(0, n - 1)
j = random.randint(0, n - 1)

if i != j:
neighbor = []
for item in current_path:
neighbor.append(item)

temp = neighbor[i]
neighbor[i] = neighbor[j]
neighbor[j] = temp

neighbor_cost = calculate_cost(graph, neighbor)

if neighbor_cost < current_cost:


current_path = neighbor
current_cost = neighbor_cost
print("Better path found:", current_path)
print("Updated cost:", current_cost)
return current_path, current_cost

n = int(input("Enter number of nodes in the graph: "))

graph = input_graph(n)

print("Adjacency Matrix:")
for i in range(n):
for j in range(n):
print(graph[i][j], end=' ')
print()

best_path, best_cost = hill_climbing(graph)

print("Best path:", best_path)


print("Best cost:", best_cost)
OUTPUT
A* SEARCH ALGORITHM

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

def is_valid(row, col):


if row >= 0 and row < ROW and col >= 0 and col < COL:
return True
else:
return False

def is_unblocked(grid, row, col):


if grid[row][col] != 0:
return True
else:
return False

def is_destination(row, col, dest):


if row == dest[0] and col == dest[1]:
return True
else:
return False

def calculate_h_value(row, col, dest):


h = abs(row - dest[0]) + abs(col - dest[1])
return h

def trace_path(cell_details, dest):


row = dest[0]
col = dest[1]
path = []
while not (cell_details[row][col].parent_i == row and cell_details[row][col].parent_j ==
col):
path.append((row, col))
temp_row = cell_details[row][col].parent_i
temp_col = cell_details[row][col].parent_j
row = temp_row
col = temp_col

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

def a_star_search(grid, src, dest):


if not is_valid(src[0], src[1]):
print("Source is invalid")
return

if not is_valid(dest[0], dest[1]):


print("Destination is invalid")
return

if not is_unblocked(grid, src[0], src[1]) or not is_unblocked(grid, dest[0], dest[1]):


print("Source or destination is blocked")
return

if is_destination(src[0], src[1], dest):


print("Source is the destination")
return

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

directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]

while len(open_list) > 0:


current = heapq.heappop(open_list)
f = current[0]
i = current[1][0]
j = current[1][1]

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 closed_list[new_i][new_j] and is_unblocked(grid, new_i, new_j):


g_new = cell_details[i][j].g + 1.0
h_new = calculate_h_value(new_i, new_j, dest)
f_new = g_new + h_new

if cell_details[new_i][new_j].f == 0.0 or cell_details[new_i][new_j].f > f_new:


heapq.heappush(open_list, (f_new, (new_i, new_j)))
cell_details[new_i][new_j].f = f_new
cell_details[new_i][new_j].g = g_new
cell_details[new_i][new_j].h = h_new
cell_details[new_i][new_j].parent_i = i
cell_details[new_i][new_j].parent_j = j

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)

a_star_search(grid, src, dest)


OUTPUT
ADVERSARIAL SEARCH [TIC TAC TOC]

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 minimax(board, depth, is_maximizing):


winner = check_winner(board)
if winner is not None:
return winner
if is_maximizing:
best_score = -math.inf
for i in range(9):
if board[i] == " ":
board[i] = "X"
score = minimax(board, depth + 1, False)
board[i] = " "
best_score = max(best_score, score)
return best_score
else:
best_score = math.inf
for i in range(9):
if board[i] == " ":
board[i] = "O"
score = minimax(board, depth + 1, True)
board[i] = " "
best_score = min(best_score, score)
return best_score

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)

print("Your position:", human_pos)

if human_pos == 100:
print("Congratulations! You won!")
break

time.sleep(1)

print("\n AI's turn...")


dice = roll_dice()
print("AI rolled:", dice)
ai_pos += dice
if ai_pos > 100:
ai_pos -= dice
else:
ai_pos = move_player(ai_pos)
print(" AI position:", ai_pos)

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 get_winner(player, ai):


if player == ai:
return "It's a tie!"
elif (player == "rock" and ai == "scissors") or \
(player == "scissors" and ai == "paper") or \
(player == "paper" and ai == "rock"):
return "You win!"
else:
return "AI wins!"

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

result = get_winner(player_choice, ai_choice)


print(result)

print("******************************************************")

play_rps()
OUTPUT
FIRST ORDER LOGIC
PROGRAM

% Monkey and Banana Problem - With Action Trace

% Possible moves with resulting state


move(state(middle, onbox, middle, hasnot),
grasp,
state(middle, onbox, middle, has)).

move(state(P, onfloor, P, H),


climb,
state(P, onbox, P, H)).

move(state(P1, onfloor, P1, H),


drag(P1, P2),
state(P2, onfloor, P2, H)).

move(state(P1, onfloor, B, H),


walk(P1, P2),
state(P2, onfloor, B, H)).

% Base case: monkey has banana


canget(state(_, _, _, has), []).

% Recursive case: find a sequence of moves


canget(State1, [Move | Moves]) :-
move(State1, Move, State2),
canget(State2, Moves).
OUTPUT
FIRST ORDER LOGIC
PROGRAM

valuable(gold).

female(jane).

owns(jane, gold).

father(john, mary).

gives(john, book, 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).

may_steal(john, A) :- thief(john), likes(john, A).


OUTPUT

?- valuable(gold).

true.

?- valuable(salt).

false.

?- father(john, mary).

true.

?- female(jane).

true.

?- likes(john, X).

X = flowers ; X = apples ; X = mangoes ; X = mary ; X = burger ; X = pizza ; X = snow ;


X = dollar.

?- hates(john, Y).

Y = orange.

?- dislikes(john, Z).

Z = banana.

?- likes(mary, john), likes(john, mary).


true.
(We have likes(john, mary) but not likes(mary, john) — so unless likes(mary, john). is
added, the answer is false.)

?- likes(mary, X), likes(john, X).

X = burger ; X = pizza.

?- may_steal(john, A).

(Using the rule: may_steal(john, A) :- thief(john), likes(john, A).)

A = flowers ; apples ; mangoes ; mary ; burger ; pizza ; snow ; dollar.

?- may_steal(john, jewellery).

false.

?- may_steal(john, ball).

(John does not like ball)

false.

?- may_steal(john, snow).

true.
N-QUEENS PROBLEM
PROGRAM

def print_solution(board, N):


for i in range(N):
for j in range(N):
if board[i][j] == 1:
print("Q", end=" ")
else:
print(".", end=" ")
print()
print("\n")

def is_safe(board, row, col, N):


for i in range(col):
if board[row][i] == 1:
return False

for i, j in zip(range(row, -1, -1), range(col, -1, -1)):


if board[i][j] == 1:
return False

for i, j in zip(range(row, N), range(col, -1, -1)):


if board[i][j] == 1:
return False

return True

def solve_n_queens(board, col, N, last_solution):


if col >= N:
last_solution.clear()
for i in range(N):
last_solution.append(board[i][:]) # Copy current board
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 = []

if not solve_n_queens(board, 0, N, last_solution):


print("No solution exists")
else:
print(f"Last solution for {N}-Queens problem:")
print_solution(last_solution, N)

N = int(input("Enter the number of queens (N): "))


solve(N)
OUTPUT
TRAVELLING SALESMAN PROBLEM

PROGRAM

from itertools import permutations

def get_distance_matrix(cities):
n = len(cities)
dist = [[0] * n for _ in range(n)]

print("\nEnter distances between cities:")


for i in range(n):
for j in range(n):
if i != j:
while True:
try:
d = float(input(f"Distance from {cities[i]} to {cities[j]}: "))
dist[i][j] = d
break
except ValueError:
print("Enter a valid number.")
else:
dist[i][j] = 0
return dist

def calculate_path_cost(path, dist):


cost = 0
for i in range(len(path) - 1):
cost += dist[path[i]][path[i+1]]
cost += dist[path[-1]][path[0]] # return to starting city
return cost

def solve_tsp(cities, dist):


n = len(cities)
city_indices = list(range(n))
min_cost = float('inf')
best_path = []

for perm in permutations(city_indices[1:]):


current_path = [0] + list(perm)
cost = calculate_path_cost(current_path, dist)
if cost < min_cost:
min_cost = cost
best_path = current_path
return best_path, min_cost

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)

best_path, min_cost = solve_tsp(cities, dist_matrix)

print("\nMinimum Cost Path:")


for idx in best_path:
print(cities[idx], end=" -> ")
print(cities[best_path[0]]) # return to starting city

print(f"\nTotal travel cost: {min_cost}")

if __name__ == "__main__":
main()
OUTPUT
MULTI AGENT SYSTEM [MAZE]
PROGRAM

pip install pygame

import tkinter as tk
from tkinter import messagebox

# Maze Layout: 0 = path, 1 = wall


MAZE = [
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 1, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 1, 0, 1],
[1, 0, 1, 0, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 0, 1],
[1, 1, 1, 1, 1, 1, 0, 1],
[1, 1, 1, 1, 1, 1, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1],
]

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

def move_player(self, event):


r, c = self.player_pos
if event.keysym == "Up":
new_r, new_c = r - 1, c
elif event.keysym == "Down":
new_r, new_c = r + 1, c
elif event.keysym == "Left":
new_r, new_c = r, c - 1
elif event.keysym == "Right":
new_r, new_c = r, c + 1
else:
return

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.

FinBot supports five major roles:

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:

• Real-time financial queries like "How do I start saving for retirement?"

• Information about credit scores, loans, and interest rates

• Monthly savings progress tracking and goal setting

• Financial literacy resources and tips

• Multi-device support for financial tracking on the go

Technology Stack:

• Dialogflow / Rasa for building contextual conversational flows

• OpenAI GPT API for dynamic financial guidance (e.g., budgeting advice, investment
tips)

• Firebase for user data management and progress tracking

• Geo APIs for location-based financial assistance (e.g., finding financial advisors)

• Multilingual NLP models for broader user support.

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:

from flask import Flask, render_template, request, jsonify

import random

import re

import json

import os

# Initialize Flask app

app = Flask(__name__)

knowledge_base = {

"greetings": [

"Hello! I'm FinBot, your personal financial assistant. How can I help you today?",

"Hi there! FinBot at your service. Ready to talk money?",

"Welcome! I'm FinBot. Whether it's budgeting or investing, I've got you covered."

],

"farewells": [

"Goodbye! Stay financially savvy!",

"See you next time! Remember to track your spending!",

"Take care! Keep building your financial future!"

],

"thanks": [

"You're welcome! I'm always here to help with your finances.",

"No problem! Financial clarity is just a chat away.",

"Happy to help! Your financial health matters!"

],

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

"Think of me as your AI-powered money guide!"

],

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

"Use budgeting apps or spreadsheets to stay consistent and organized."

],

"emergency_fund": [

"An emergency fund should ideally cover 3 to 6 months of living expenses.",

"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": [

"Pay yourself first — treat savings like a fixed bill.",

"Automate transfers to savings right after payday.",

"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": [

"Mutual funds pool money from investors to buy diversified portfolios.",

"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": [

"Common loans include personal, auto, mortgage, and student loans.",

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

"Consider using tax software or a CPA if your finances are complex."

],

"insurance_basics": [

"Insurance protects you from big financial losses — health, auto, home, and life are key
types.",

"Always compare multiple quotes before buying a policy."

],

"retirement_planning": [
"Start retirement savings early to benefit from compound growth.",

"401(k)s and IRAs are great retirement vehicles with tax advantages.",

"Aim to replace about 70–80% of your pre-retirement income."

],

"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": [

"Set SMART goals — Specific, Measurable, Achievable, Relevant, Time-bound.",

"Break big goals into smaller monthly milestones for motivation."

],

"student_loans": [

"Know the difference between federal and private loans — repayment options differ.",

"Consider income-driven repayment if you’re struggling to pay."

],

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

"Get pre-approved before house hunting to know your budget."

],

"fraud_prevention": [

"Monitor your credit report and bank activity regularly.",

"Use two-factor authentication and avoid public Wi-Fi for banking."


],

"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": []

# Function to preprocess text (simplified)

def preprocess_text(text):

text = text.lower().strip()

text = re.sub(r'[^\w\s]', '', text)

return text

# Load knowledge base

if os.path.exists('ecobot_knowledge_base.json'):

with open('ecobot_knowledge_base.json', 'r', encoding="utf-8") as f:

knowledge_base = json.load(f)

else:

# Create simplified knowledge base with all original categories


#

# Save initial knowledge base

with open('ecobot_knowledge_base.json', 'w', encoding="utf-8") as f:

json.dump(knowledge_base, f, indent=4)

# User role tracking (simplified)

user_info = {

"current_role": "unknown",

"waste_type": None

# Simple intent detection (without spaCy)

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"

elif re.search(r'\b(bye|goodbye|see you|farewell)\b', user_input):

return "farewells"

elif re.search(r'\b(thanks|thank you|appreciate)\b', user_input):

return "thanks"

elif re.search(r'\b(who are you|what are you|your name|your identity)\b', user_input):

return "identity"

# Financial literacy and planning

elif re.search(r'\b(budget|budgeting|spending plan|track expenses)\b', user_input):


return "budgeting_tips"

elif re.search(r'\b(emergency fund|unexpected expenses|rainy day)\b', user_input):

return "emergency_fund"

elif re.search(r'\b(save money|saving tips|how to save|best way to save)\b', user_input):

return "saving_tips"

elif re.search(r'\b(invest|investment|etf|index fund|stock market)\b', user_input):

return "investment_basics"

elif re.search(r'\b(stock.*bond|difference between stocks and bonds)\b', user_input):

return "stock_vs_bonds"

elif re.search(r'\b(mutual fund|sip|investment fund)\b', user_input):

return "mutual_funds"

elif re.search(r'\b(credit score|fico|credit report|improve credit)\b', user_input):

return "credit_score_basics"

elif re.search(r'\b(loans?|loan types|borrow|debt)\b', user_input):

return "loan_types"

elif re.search(r'\b(pay off debt|repay loans|snowball method|avalanche)\b', user_input):

return "debt_repayment_strategies"

elif re.search(r'\b(tax filing|income tax|file taxes|tax tips)\b', user_input):

return "tax_filing_tips"

elif re.search(r'\b(insurance|health insurance|car insurance|life insurance|coverage)\b',


user_input):

return "insurance_basics"

elif re.search(r'\b(retirement|401k|ira|pension|retire)\b', user_input):

return "retirement_planning"

elif re.search(r'\b(compound interest|interest growth|compound return)\b', user_input):

return "compound_interest"

elif re.search(r'\b(financial goal|save for|plan savings)\b', user_input):

return "financial_goals"
elif re.search(r'\b(student loan|college debt|education loan)\b', user_input):

return "student_loans"

elif re.search(r'\b(credit card|credit utilization|credit limit)\b', user_input):

return "credit_card_tips"

elif re.search(r'\b(mortgage|home loan|buy house|house loan)\b', user_input):

return "mortgage_tips"

elif re.search(r'\b(fraud|identity theft|scam|protect info)\b', user_input):

return "fraud_prevention"

elif re.search(r'\b(financial literacy|learn finance|understand money)\b', user_input):

return "financial_literacy"

# Default fallback

return "unknown"

# Function to generate response (simplified)

def generate_response(user_input):

intent = detect_intent(user_input)

print(intent)

# Check if we have responses for this 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": ""

# Process user message

def process_message(user_input):

global conversation_context

# Check if we're in learning mode

if conversation_context["learning_mode"]:

if user_input.lower() in ["no", "nevermind", "cancel"]:

conversation_context["learning_mode"] = False

return "No problem! Let's continue our eco-conversation."

elif conversation_context["question_to_learn"]:

# Save the new knowledge

knowledge_base["learned_responses"][conversation_context["question_to_learn"]] =
user_input

with open('ecobot_knowledge_base.json', 'w') as f:

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

elif user_input.lower() == "yes":


conversation_context["question_to_learn"] = conversation_context["last_user_input"]

return "Great! Please provide the eco-friendly answer to your question."

# Regular conversation flow

conversation_context["last_user_input"] = user_input

response = generate_response(user_input)

# Check if we should enter learning mode

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

print("User said:", user_input) # Debug log

bot_reply = process_message(user_input)

return jsonify({"response": bot_reply})

if __name__ == "__main__":

app.run(debug=True)
SCREENSHOTS:
RESULT:

Thus, we developed FinBot, an AI-powered chatbot providing personalized financial guidance


for investors, savers, borrowers, and financial planners. Integrated AI-driven Natural Language
Processing (NLP) and data analysis were implemented successfully to support budgeting, debt
management, investment advice, and retirement planning.

You might also like