0% found this document useful (0 votes)
2 views9 pages

Class Graph

The document contains multiple Python classes and functions for various algorithms and applications, including graph traversal (DFS and BFS), a Tic-Tac-Toe game with AI, Kruskal's algorithm for finding a minimum spanning tree, a N-Queens solver, a simple chatbot, and an expert system for medical diagnosis. Each section includes code for implementing the respective functionality, showcasing data structures and algorithms. The main program sections demonstrate how to use these functions interactively.

Uploaded by

Ruchita Rajput
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)
2 views9 pages

Class Graph

The document contains multiple Python classes and functions for various algorithms and applications, including graph traversal (DFS and BFS), a Tic-Tac-Toe game with AI, Kruskal's algorithm for finding a minimum spanning tree, a N-Queens solver, a simple chatbot, and an expert system for medical diagnosis. Each section includes code for implementing the respective functionality, showcasing data structures and algorithms. The main program sections demonstrate how to use these functions interactively.

Uploaded by

Ruchita Rajput
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

class Graph:

def __init__(self):
[Link] = {}

# Add edge (undirected)


def add_edge(self, u, v):
if u not in [Link]:
[Link][u] = []
if v not in [Link]:
[Link][v] = []

[Link][u].append(v)
[Link][v].append(u)

# ---------------- DFS (Recursive) ----------------


def dfs(self, node, visited=None):
if visited is None:
visited = set()

# Mark current node as visited


[Link](node)
print(node, end=" ")

# Visit all neighbors


for neighbor in [Link][node]:
if neighbor not in visited:
[Link](neighbor, visited)

# ---------------- BFS ----------------


def bfs(self, start):
visited = set()
queue = []

# Start with the first node


[Link](start)
[Link](start)

while queue:
node = [Link](0)
print(node, end=" ")

for neighbor in [Link][node]:


if neighbor not in visited:
[Link](neighbor)
[Link](neighbor)

# ---------------- MAIN PROGRAM ----------------


if __name__ == "__main__":
g = Graph()

# Adding edges (Undirected graph)


g.add_edge(1, 2)
g.add_edge(1, 3)
g.add_edge(2, 4)
g.add_edge(2, 5)
g.add_edge(3, 6)

print("DFS Traversal:")
[Link](1)

print("\nBFS Traversal:")
[Link](1)
def print_board(b):
for i in range(0, 9, 3):
print(b[i], "|", b[i+1], "|", b[i+2])
print()

def check_win(b):
wins = [
[0,1,2],[3,4,5],[6,7,8],
[0,3,6],[1,4,7],[2,5,8],
[0,4,8],[2,4,6]
]
for w in wins:
if b[w[0]] == b[w[1]] == b[w[2]] != ' ':
return b[w[0]]
if ' ' not in b:
return "Draw"
return None

def heuristic(b):
score = 0
wins = [
[0,1,2],[3,4,5],[6,7,8],
[0,3,6],[1,4,7],[2,5,8],
[0,4,8],[2,4,6]
]
for w in wins:
line = [b[w[0]], b[w[1]], b[w[2]]]
if [Link]('X') == 2 and [Link](' ') == 1:
score += 10
elif [Link]('O') == 2 and [Link](' ') == 1:
score -= 10
return score

def best_move(board):
best = -1000
move = -1

print("Evaluating moves:")

for i in range(9):
if board[i] == ' ':
board[i] = 'X'

# g(n)
if check_win(board) == 'X':
print(f"Move {i} → f = 100 (WIN)")
board[i] = ' '
return i

g=0
h = heuristic(board)
f=g+h

print(f"Move {i} → g={g}, h={h}, f={f}")

board[i] = ' '

if f > best:
best = f
move = i

return move

# MAIN
board = [' '] * 9

while True:
m = best_move(board)
board[m] = 'X'
print("Computer:")
print_board(board)

result = check_win(board)
if result:
print_board(board)
print("Result:", result)
break

user = int(input("Enter move: "))


if board[user] == ' ':
board[user] = 'O'
else:
print("Invalid")

print("You:")
print_board(board)

if check_win(board):
print("Winner:", check_win(board))
break
def find(parent, i):
if parent[i] == i:
return i
return find(parent, parent[i])

def union(parent, x, y):


parent[x] = y

# -------- INPUT --------


v = int(input("Enter number of vertices: "))
e = int(input("Enter number of edges: "))

edges = []

print("Enter edges (u v weight):")


for _ in range(e):
u, v2, w = map(int, input().split())
[Link]((w, u, v2))

# Step 1: Sort edges


[Link]()

parent = []
for i in range(v):
[Link](i)

mst = []

# Kruskal
for w, u, v2 in edges:
x = find(parent, u)
y = find(parent, v2)

if x != y:
[Link]((u, v2, w))
union(parent, x, y)

# OUTPUT
print("\nMinimum Spanning Tree:")
for u, v2, w in mst:
print(u, "--", v2, "=", w)
def is_safe(board, row, col, n):
# check column
for i in range(row):
if board[i][col] == 1:
return False

# left diagonal
i, j = row-1, col-1
while i >= 0 and j >= 0:
if board[i][j] == 1:
return False
i -= 1
j -= 1

# right diagonal
i, j = row-1, col+1
while i >= 0 and j < n:
if board[i][j] == 1:
return False
i -= 1
j += 1

return True

def solve(board, row, n):


if row == n:
return True

for col in range(n):


if is_safe(board, row, col, n):
board[row][col] = 1

if solve(board, row+1, n):


return True

# backtrack
board[row][col] = 0

return False

# -------- INPUT --------


n = int(input("Enter number of queens: "))

board = []
for _ in range(n):
[Link]([0]*n)
# -------- SOLVE --------
if solve(board, 0, n):
print("Solution:")
for row in board:
print(row)
else:
print("No solution")
def chatbot():
print("Chatbot: Welcome to Clinic Help Desk!")

while True:
user = input("You: ").lower()

if "hi" in user or "hello" in user:


print("Chatbot: Hello! How can I assist you?")

elif "timing" in user or "time" in user:


print("Chatbot: Clinic is open from 10 AM to 5 PM.")

elif "fee" in user or "cost" in user:


print("Chatbot: Consultation fee is $20.")

elif "day" in user or "available" in user:


print("Chatbot: We are open Monday to Saturday.")

elif "doctor" in user or "specialist" in user:


print("Chatbot: We have general physicians and specialists available.")

elif "location" in user or "address" in user:


print("Chatbot: We are located near City Center, Main Road.")

elif "bye" in user or "exit" or "ok" or "okay" in user:


print("Chatbot: Thank you for contacting!.")
break

else:
print("Chatbot: I can help with timings, fee, days, doctor info, and location.")

chatbot()
def expert_system():
print("Expert System: Medical Diagnosis")

fever = input("Do you have fever? (yes/no): ").lower()


cough = input("Do you have cough? (yes/no): ").lower()
headache = input("Do you have headache? (yes/no): ").lower()
fatigue = input("Do you feel fatigue? (yes/no): ").lower()
sore_throat = input("Do you have sore throat? (yes/no): ").lower()

# Multiple symptom rules (more serious)


if fever == "yes" and cough == "yes" and fatigue == "yes":
print("Diagnosis: You may have Flu.")

elif fever == "yes" and headache == "yes" and fatigue == "yes":


print("Diagnosis: Possible Viral Infection.")

elif fever == "yes" and cough == "yes" and sore_throat == "yes":


print("Diagnosis: Possible COVID-like symptoms.")

# Two symptom rules


elif cough == "yes" and sore_throat == "yes":
print("Diagnosis: You may have Common Cold.")

elif fever == "yes" and headache == "yes":


print("Diagnosis: Mild infection or stress.")

# Single symptom rules


elif fever == "yes":
print("Diagnosis: Mild fever. Take rest and stay hydrated.")

elif cough == "yes":


print("Diagnosis: You may have cough or throat irritation.")

elif headache == "yes":


print("Diagnosis: You may have headache due to stress.")

elif fatigue == "yes":


print("Diagnosis: You may be tired. Take proper rest.")

elif sore_throat == "yes":


print("Diagnosis: You may have throat infection.")

else:
print("Diagnosis: You seem fine. Stay healthy!")

expert_system()

You might also like