Internal Lab
Internal Lab
INTERNAL LAB
% male(Name).
male(john).
male(mike).
male(tom).
% female(Name).
female(susan).
female(mary).
female(lisa).
% sibling(X, Y) :- X and Y are siblings if they share a parent and are not the same person.
sibling(X, Y) :-
parent(P, X),
parent(P, Y),
X \= Y.
OUTPUT
?- father(john, X). Who are John’s children? X = mary ; X = mike.
disease(cold) :-
symptom(runny_nose),
symptom(sneezing),
symptom(sore_throat).
disease(malaria) :-
symptom(fever),
symptom(chills),
symptom(sweating),
symptom(headache).
disease(typhoid) :-
symptom(fever),
symptom(abdominal_pain),
symptom(loss_of_appetite),
symptom(headache).
disease(covid19) :-
symptom(fever),
symptom(cough),
symptom(shortness_of_breath),
symptom(loss_of_taste_or_smell).
ask_symptoms([]).
ask_symptoms([H|T]) :-
ask(H),
ask_symptoms(T).
OUTPUT
?- [medical_diagnosis].
?- start.
--- Welcome to the Medical Diagnosis Expert System ---
Do you have fever? (yes/no): yes
Do you have cough? (yes/no): yes
Do you have sore_throat? (yes/no): yes
Do you have body_ache? (yes/no): yes
...
You may have flu.
# ------------------------------------------
# Graph Traversal using DFS and BFS in Python
# ------------------------------------------
# --------------------------
# Depth-First Search (DFS)
# --------------------------
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
[Link](start)
print(start, end=' ')
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
# --------------------------
# Breadth-First Search (BFS)
# --------------------------
def bfs(graph, start):
visited = set()
queue = deque([start])
[Link](start)
while queue:
vertex = [Link]()
print(vertex, end=' ')
for neighbor in graph[vertex]:
if neighbor not in visited:
[Link](neighbor)
[Link](neighbor)
# --------------------------
# Main Program
# --------------------------
if __name__ == "__main__":
print("Graph Traversal using DFS and BFS\n")
# ---------------------------------------------
# A* Search Algorithm Implementation in Python
# ---------------------------------------------
# -----------------------------------------------------
# A* Search Algorithm Function
# -----------------------------------------------------
def a_star_search(graph, start, goal, heuristic):
# Priority queue for frontier nodes (min-heap)
open_list = []
heappush(open_list, (0 + heuristic[start], 0, start, [start])) # (f, g, node, path)
visited = set()
while open_list:
f, g, current, path = heappop(open_list)
if current in visited:
continue
[Link](current)
# If goal found
if current == goal:
print("Path found:", " -> ".join(path))
print("Total cost:", g)
return
# Explore neighbors
for neighbor, cost in graph[current].items():
if neighbor not in visited:
g_new = g + cost
f_new = g_new + heuristic[neighbor]
heappush(open_list, (f_new, g_new, neighbor, path + [neighbor]))
start_node = 'A'
goal_node = 'E'
OUTPUT
A* Search Algorithm Example
[Link] the Mini max algorithm for a simple game (e.g., Tic Tac Toe).
# ---------------------------------------------------
# Tic Tac Toe Game with Minimax Algorithm (Human vs AI)
# ---------------------------------------------------
import math
# -----------------------------
# Minimax Algorithm Definition
# -----------------------------
def minimax(b, depth, is_maximizing):
# Base cases
if check_winner(b, "O"):
return 1
elif check_winner(b, "X"):
return -1
elif is_draw(b):
return 0
if is_maximizing: # AI’s turn
best_score = -[Link]
for i in range(9):
if b[i] == " ":
b[i] = "O"
score = minimax(b, depth + 1, False)
b[i] = " "
best_score = max(score, best_score)
return best_score
else: # Human’s turn
best_score = [Link]
for i in range(9):
if b[i] == " ":
b[i] = "X"
score = minimax(b, depth + 1, True)
b[i] = " "
best_score = min(score, best_score)
return best_score
while True:
# Human move
try:
user_move = int(input("Enter your move (1-9): ")) - 1
if user_move < 0 or user_move > 8 or board[user_move] != " ":
print("Invalid move! Try again.")
continue
except ValueError:
print("Please enter a valid number (1-9).")
continue
board[user_move] = "X"
# AI move
print("AI is thinking...")
ai_move = best_move()
board[ai_move] = "O"
print_board()
# Check if AI wins
if check_winner(board, "O"):
print("💻 AI wins!")
break
output
| |
---------
| |
---------
| |
💻 AI wins!
#define MAX 50
int symcount = 0;
int locctr = 0;
printf("\nPASS 1:\n");
fscanf(fp1, "%s", opcode);
if (strcmp(opcode, "START") == 0) {
fscanf(fp1, "%d", &locctr);
printf("Starting address = %d\n", locctr);
} else {
locctr = 0;
rewind(fp1);
}
// Label present?
if (strcmp(label, "**") != 0) {
strcpy(symtab[symcount].label, label);
symtab[symcount].addr = locctr;
symcount++;
}
if (opIndex == -1)
printf("Error: Invalid opcode %s\n", opcode);
else if (strcmp(opcode, "DS") == 0)
locctr += atoi(operand);
else if (strcmp(opcode, "DC") == 0)
locctr += 1;
else
locctr += 1;
}
printf("\nSymbol Table:\n");
printf("Label\tAddress\n");
for (i = 0; i < symcount; i++)
printf("%s\t%d\n", symtab[i].label, symtab[i].addr);
rewind(fp2);
fscanf(fp2, "%s", opcode);
if (strcmp(opcode, "START") == 0) {
fscanf(fp2, "%s", operand);
} else {
rewind(fp2);
}
opIndex = search_optab(opcode);
if (opIndex == -1)
printf("Error: Unknown opcode %s\n", opcode);
else if (strcmp(opcode, "DC") == 0)
printf("%s\t%s\t%s\t-->\t%s\n", label, opcode, operand, operand);
else if (strcmp(opcode, "DS") == 0)
printf("%s\t%s\t%s\t-->\t(No code)\n", label, opcode, operand);
else {
symIndex = search_symtab(operand);
if (symIndex == -1)
printf("%s\t%s\t%s\t-->\t%s ?\n", label, opcode, operand, optab[opIndex].code);
else
printf("%s\t%s\t%s\t-->\t%s %d\n", label, opcode, operand, optab[opIndex].code,
symtab[symIndex].addr);
}
}
}
int main() {
FILE *fp;
fp = fopen("[Link]", "r");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
pass1(fp);
rewind(fp);
pass2(fp);
fclose(fp);
return 0;
}
START 100
LOOP MOVER AREG,NUM
** ADD BREG,ONE
** SUB CREG,TWO
** MOVEM AREG,RESULT
END
NUM DS 1
ONE DC 1
TWO DC 2
RESULT DS 1
OUTPUT
PASS 1:
Starting address = 100
Symbol Table:
Label Address
LOOP 100
NUM 104
ONE 105
TWO 106
RESULT 107
Program length = 108
/*
---------------------------------------------------------------
Simple Macro Processor in C
Author: Educational Example
Description:
- Reads assembly code with macros.
- Builds:
MNT: Macro Name Table
MDT: Macro Definition Table
- Expands macros in the output file.
Example Input ([Link]):
MACRO
INCR &A,&B
LDA &A
ADD &B
STA &A
MEND
START
INCR NUM1, NUM2
INCR TOTAL, FIVE
END
---------------------------------------------------------------
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 50
char mdt[MAX][50];
int mntc = 0, mdtc = 0;
if (strcmp(opcode, "MACRO") == 0) {
// Read macro prototype
fgets(line, sizeof(line), fp);
sscanf(line, "%s %s", mnt[mntc].name, operand);
mnt[mntc].mdt_index = mdtc;
mntc++;
void displayTables() {
printf("\nMACRO NAME TABLE (MNT):\n");
printf("Index\tName\tMDT Index\n");
for (int i = 0; i < mntc; i++)
printf("%d\t%s\t%d\n", i + 1, mnt[i].name, mnt[i].mdt_index);
if (strcmp(opcode, "MACRO") == 0) {
// Skip macro definition
while (fgets(line, sizeof(line), fp)) {
sscanf(line, "%s", opcode);
if (strcmp(opcode, "MEND") == 0)
break;
}
} else {
int found = -1;
for (i = 0; i < mntc; i++) {
if (strcmp(opcode, mnt[i].name) == 0) {
found = i;
break;
}
}
if (found != -1) {
// Expand macro
int k = mnt[found].mdt_index;
while (strcmp(mdt[k], "MEND") != 0) {
fprintf(fpout, "%s", mdt[k]);
k++;
}
} else {
fprintf(fpout, "%s", line);
}
}
}
}
int main() {
FILE *fp, *fpout;
fp = fopen("[Link]", "r");
fpout = fopen("[Link]", "w");
// Display tables
displayTables();
fclose(fp);
fclose(fpout);
return 0;
}
Output
MACRO NAME TABLE (MNT):
Index Name MDT Index
1 INCR 0
/*
-------------------------------------------------------------
Simple Linux Shell in C
Author: Educational Example
Description:
- A basic shell that executes Linux commands.
- Supports built-in commands:
cd <dir> → change directory
exit → exit the shell
- Uses fork(), execvp(), and wait().
-------------------------------------------------------------
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
if (args[0] == NULL) {
return; // Empty command
}
// Built-in 'exit'
if (strcmp(args[0], "exit") == 0) {
printf("Exiting shell...\n");
exit(0);
}
// Built-in 'cd'
if (strcmp(args[0], "cd") == 0) {
if (args[1] == NULL) {
fprintf(stderr, "cd: missing argument\n");
} else {
if (chdir(args[1]) != 0) {
perror("cd failed");
}
}
return;
}
if (pid < 0) {
perror("Fork failed");
return;
} else if (pid == 0) {
// Child process: execute the command
if (execvp(args[0], args) == -1) {
perror("Command not found");
}
exit(EXIT_FAILURE);
} else {
// Parent process: wait for the child to finish
waitpid(pid, &status, 0);
}
}
int main() {
char input[MAX_INPUT];
char *args[MAX_ARGS];
printf("======================================\n");
printf(" Simple Linux Shell in C (myshell) \n");
printf(" Type 'exit' to quit.\n");
printf("======================================\n");
while (1) {
read_command(input);
parse_command(input, args);
execute_command(args);
}
return 0;
}
Output
======================================
Simple Linux Shell in C (myshell)
Type 'exit' to quit.
======================================
myshell> pwd
/home/user
myshell> ls
Documents Downloads main.c myshell Pictures
myshell> cd Documents
myshell> pwd
/home/user/Documents
myshell> echo Hello World
Hello World
myshell> exit
Exiting shell...
[Link] shell scripts for file operations, process creation, and monitoring.
#!/bin/bash
# -----------------------------------------------
# File Operations Script
# Demonstrates file creation, copying, renaming, and deletion
# -----------------------------------------------
# Copy file
echo "Enter name of copy file:"
read copyname
cp "$filename" "$copyname"
echo "File copied as '$copyname'."
# Rename file
echo "Enter new name to rename '$filename':"
read newname
mv "$filename" "$newname"
echo "File renamed to '$newname'."
# Delete file
echo "Do you want to delete '$copyname'? (y/n)"
read ans
if [ "$ans" = "y" ]; then
rm "$copyname"
echo "File '$copyname' deleted."
else
echo "File not deleted."
Fi
Run command
chmod +x file_operations.sh
./file_operations.sh
#!/bin/bash
# --------------------------------------------------
# Process Creation Script
# Demonstrates creating background and foreground processes
# --------------------------------------------------
#!/bin/bash
# --------------------------------------------------
# Process Monitoring Script
# Monitors a given process name and reports its status
# --------------------------------------------------
echo "=== PROCESS MONITORING ==="
echo "Enter process name to monitor (e.g., bash, firefox, sshd):"
read pname
while true
do
pid=$(pgrep "$pname" | head -n 1)
if [ -z "$pid" ]; then
echo "Process '$pname' is NOT running."
else
echo "Process '$pname' is running with PID: $pid"
fi
echo "Checking again in 5 seconds... (Press Ctrl+C to stop)"
sleep 5
done
OUTPUT
int main() {
pid_t pid;
// Create a pipe
if (pipe(pipefd) == -1) {
perror("pipe failed");
exit(1);
}
if (pid < 0) {
perror("fork failed");
exit(1);
}
else if (pid == 0) {
// -------- Child Process --------
close(pipefd[1]); // close write end
[Link] AI logic (search/expert system) into a shell script or system utility for task
automation.
#!/bin/bash
# ---------------------------------------------------
# AI Logic in Shell Script - System Helper Expert
# ---------------------------------------------------
# This script recommends actions based on system state
# Uses simple rule-based AI (if-then logic)
# ---------------------------------------------------
# Main AI loop
while true; do
echo
echo "Choose a system check:"
echo "1. CPU Usage"
echo "2. Memory Usage"
echo "3. Disk Usage"
echo "4. Top Process Suggestion"
echo "5. Exit"
read -p "Enter your choice [1-5]: " choice
case $choice in
1) check_cpu ;;
2) check_memory ;;
3) check_disk ;;
4) suggest_process ;;
5) echo "Exiting SysHelper..."; exit 0 ;;
*) echo "Invalid choice. Try again." ;;
esac
done
OUTPUT
Welcome to SysHelper - AI-powered System Utility
Choose a system check:
1. CPU Usage
2. Memory Usage
3. Disk Usage
4. Top Process Suggestion
5. Exit
Enter your choice [1-5]: 1
Current CPU usage: 82%
AI Suggestion: CPU usage is high! Consider killing unnecessary processes.
12. Develop an AI-powered system utility (e.g., Intelligent File Manager, AI Bot for CLI
commands).
#!/bin/bash
# -------------------------------------------------------
# AI File Manager - Intelligent CLI Utility
# -------------------------------------------------------
# Features:
# - Lists files intelligently
# - Suggests deletion of large files
# - Finds duplicate files
# - Organizes files by type
# - Rule-based AI logic for recommendations
# -------------------------------------------------------
echo "=========================================="
echo " AI-Powered Intelligent File Manager"
echo "=========================================="
case $choice in
1) list_files ;;
2) suggest_large_files ;;
3) find_duplicates ;;
4) organize_by_type ;;
5) echo "Exiting AI File Manager..."; exit 0 ;;
*) echo "Invalid choice. Try again." ;;
esac
done
output
==========================================
AI-Powered Intelligent File Manager
==========================================
Choose an action:
1. List files
2. Suggest large files for cleanup
3. Find duplicate files
4. Organize files by type
5. Exit
Enter choice [1-5]: 2
Scanning for files larger than 100MB...
AI Suggestion: Consider deleting or archiving these large files:
./movie.mp4
./[Link]