DSA Paractical by Me
DSA Paractical by Me
Code :
class Node:
def __init__(self, name="", telephone=""):
self.name = name
self.telephone = telephone
class Hashing:
def __init__(self):
self.size = 100
self.data = [[] for _ in range(self.size)] # Separate Chaining - Each slot is a list
def ascii_generator(self, s):
total = 0
for char in s:
total += ord(char)
return total % self.size
def create_record(self, name, telephone):
k = self.ascii_generator(name)
record = Node(name, telephone)
self.data[k].append(record) # Inserting the record at the appropriate slot
def search_record(self, name):
k = self.ascii_generator(name)
comparisons = 0
for record in self.data[k]:
comparisons += 1
if record.name == name:
print("\nRecord found")
print("Name:", record.name)
print("Telephone:", record.telephone)
break
else:
print("Record not found")
# print(comparisons)
return comparisons
def delete_record(self, name):
k = self.ascii_generator(name)
deleted = False
for record in self.data[k]:
if record.name == name:
self.data[k].remove(record)
print("\nRecord deleted successfully")
deleted = True
break
if not deleted:
print("Record not found")
def update_record(self, name):
k = self.ascii_generator(name)
updated = False
for record in self.data[k]:
if record.name == name:
print("Enter the new telephone number:")
new_telephone = input()
record.telephone = new_telephone
print("\nRecord updated successfully")
updated = True
break
if not updated:
print("Record not found")
def display_record(self):
print("\tName\t\tTelephone")
for slot in self.data:
for record in slot:
print("\t" + record.name + "\t\t" + record.telephone)
if __name__ == "__main__":
s = Hashing()
loop = True
while loop:
print("\n-------------------------")
print(" Telephone book Database ")
print("-------------------------")
print("1. Create Record")
print("2. Display Record")
print("3. Search Record")
print("4. Update Record")
print("5. Delete Record")
print("6. Exit")
choice = int(input("enter your choice: "))
if choice == 1:
print("Enter name:")
name = input()
print("Enter telephone number:")
telephone = input()
s.create_record(name, telephone)
elif choice == 2:
s.display_record()
elif choice == 3:
print("Enter the name:")
name = input()
comparisons = s.search_record(name)
print("Number of comparisons required:", comparisons)
elif choice == 4:
print("Enter the name:")
name = input()
s.update_record(name)
elif choice == 5:
print("Enter name to delete:")
name = input()
s.delete_record(name)
elif choice == 6:
loop = False
else:
print("You entered something wrong!")
Output :
PS C:\Suraj\SPPU\Submission\DSA\Sppu-Dsa-main\Sppu-Dsa-main> python .\
01telephone-db-hashing.py
-------------------------
Telephone book Database
-------------------------
1. Create Record
2. Display Record
3. Search Record
4. Update Record
5. Delete Record
6. Exit
enter your choice: 1
Enter name:
Suraj
Enter telephone number:
9090909090
-------------------------
Telephone book Database
-------------------------
1. Create Record
2. Display Record
3. Search Record
4. Update Record
5. Delete Record
6. Exit
enter your choice: 1
Enter name:
Savita
Enter telephone number:
1010101010
-------------------------
Telephone book Database
-------------------------
1. Create Record
2. Display Record
3. Search Record
4. Update Record
5. Delete Record
6. Exit
enter your choice: 1
Enter name:
Papa
Enter telephone number:
2020202020
-------------------------
Telephone book Database
-------------------------
1. Create Record
2. Display Record
3. Search Record
4. Update Record
5. Delete Record
6. Exit
enter your choice: 1
Enter name:
Anushka
Enter telephone number:
3030303030
-------------------------
Telephone book Database
-------------------------
1. Create Record
2. Display Record
3. Search Record
4. Update Record
5. Delete Record
6. Exit
enter your choice: 2
Name Telephone
Anushka 3030303030
Savita 1010101010
Suraj 9090909090
Papa 2020202020
-------------------------
Telephone book Database
-------------------------
1. Create Record
2. Display Record
3. Search Record
4. Update Record
5. Delete Record
6. Exit
enter your choice: 3
Enter the name:
Suraj
Record found
Name: Suraj
Telephone: 9090909090
Number of comparisons required: 1
-------------------------
Telephone book Database
-------------------------
1. Create Record
2. Display Record
3. Search Record
4. Update Record
5. Delete Record
6. Exit
enter your choice: 6
PS C:\Suraj\SPPU\Submission\DSA\Sppu-Dsa-main\Sppu-Dsa-main>
Practical 02: To create ADT that implements the set and concept
Code :
class Node:
def __init__(self, key=None, value=None):
self.key = key
self.value = value
self.next = None
class HashDictionary:
def __init__(self, size):
self.size = size
self.table = [None] * size
def hash_function(self, key):
return hash(key) % self.size
def insert(self, key, value):
index = self.hash_function(key)
new_node = Node(key, value)
if self.table[index] is None:
self.table[index] = new_node
# ************with replacement *************
else:
current = self.table[index]
while current:
if current.key == key:
current.value = value # Replace the existing value
return
if current.next is None:
break
current = current.next
current.next = new_node
# **************without replacement ************
# else:
# current = self.table[index]
# while current.next:
# current = current.next
# current.next = new_node
# ----------------------
def find(self, key):
index = self.hash_function(key)
current = self.table[index]
while current:
if current.key == key:
return current.value
current = current.next
return None
def delete(self, key):
index = self.hash_function(key)
if self.table[index] is None:
return
if self.table[index].key == key:
self.table[index] = self.table[index].next
return
# chaining deletion
current = self.table[index]
while current.next:
if current.next.key == key:
current.next = current.next.next
return
current = current.next
def display(self):
print("Dictionary Contents:")
for index in range(self.size):
current = self.table[index]
while current:
print(f"Key: {current.key}, Value: {current.value}")
current = current.next
if __name__ == "__main__":
size = int(input("Enter the size of the hash table: "))
dictionary = HashDictionary(size)
while True:
print("\nDictionary Operations")
print("1. Insert")
print("2. Search")
print("3. Delete")
print("4. Display")
print("5. Exit")
choice = int(input("Enter choice: "))
if choice == 1:
key = input("Enter key: ")
value = input("Enter value: ")
dictionary.insert(key, value)
print("Key-Value pair inserted successfully.")
elif choice == 2:
key = input("Enter key to find: ")
value = dictionary.find(key)
if value is not None:
print(f"Value: {value}")
else:
print("Key not found.")
elif choice == 3:
key = input("Enter key to delete: ")
dictionary.delete(key)
print("Key deleted successfully.")
elif choice == 4:
dictionary.display()
elif choice == 5:
break
else:
print("Invalid choice. Please try again.")
Output :
PS C:\Suraj\SPPU\Submission\DSA\Sppu-Dsa-main\Sppu-Dsa-main> python .\
02DictionaryADT-functs.py
Enter the size of the hash table: 5
Dictionary Operations
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter choice: 1
Enter key: G
Enter value: 5
Key-Value pair inserted successfully.
Dictionary Operations
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter choice: 1
Enter key: F
Enter value: 4
Key-Value pair inserted successfully.
Dictionary Operations
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter choice: 1
Enter key: D
Enter value: 3
Key-Value pair inserted successfully.
Dictionary Operations
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter choice: 1
Enter key: J
Enter value: 9
Key-Value pair inserted successfully.
Dictionary Operations
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter choice: 1
Enter key: A
Enter value: 1
Key-Value pair inserted successfully.
Dictionary Operations
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter choice: 1
Enter key: C
Enter value: 1
Key-Value pair inserted successfully.
Dictionary Operations
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter choice: 4
Dictionary Contents:
Key: J, Value: 9
Key: A, Value: 1
Key: D, Value: 3
Key: C, Value: 1
Key: G, Value: 5
Key: F, Value: 4
Dictionary Operations
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter choice: 2
Enter key to find: G
Value: 5
Dictionary Operations
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter choice: 5
PS C:\Suraj\SPPU\Submission\DSA\Sppu-Dsa-main\Sppu-Dsa-main>
Practical 03 : Implementation of Binary Search Tree
Name : Suraj Surve
Roll no. : SA61
Code:
#include <iostream>
#include <string>
using namespace std;
struct node // Node Declaration
{
string label;
//char label[10];
int ch_count;
struct node *child[10];// array of pointers
} * root;
class BookTree // Class Declaration
{
public:
void create_tree();
void display(node *r1);
BookTree()
{
root = NULL;
}
};
void BookTree::create_tree()
{
int tbooks, tchapters, i, j, k;
root = new node;
cout << "Enter name of book : ";
cin.get();
getline(cin, root->label);
cout << "Enter number of chapters in book : ";
cin >> tchapters;
root->ch_count = tchapters;
for (i = 0; i < tchapters; i++)
{
root->child[i] = new node;
cout << "Enter the name of Chapter " << i + 1 << " : ";
cin.get();
getline(cin, root->child[i]->label);
cout << "Enter number of sections in Chapter : " << root->child[i]->label << " : ";
cin >> root->child[i]->ch_count;
for (j = 0; j < root->child[i]->ch_count; j++)
{
root->child[i]->child[j] = new node;
cout << "Enter Name of Section " << j + 1 << " : ";
cin.get();
getline(cin, root->child[i]->child[j]->label);
}
}
}
void BookTree::display(node *r1)
{
int i, j, k, tchapters;
if (r1 != NULL)
{
cout << "\n-----Book Overview-----";
cout << "\n Book title : " << r1->label;
tchapters = r1->ch_count;
for (i = 0; i < tchapters; i++)
{
cout << "\nChapter " << i + 1;
cout << " : " << r1->child[i]->label;
cout << "\nSections : ";
for (j = 0; j < r1->child[i]->ch_count; j++)
{
cout << " "<< r1->child[i]->child[j]->label;
}
}
}
cout << endl;
}
int main()
{
int choice;
BookTree BookTree;
while (1)
{
cout << "\nBook Tree Creation" << endl;
cout << "1.Create" << endl;
cout << "2.Display" << endl;
cout << "3.Quit" << endl;
cout << "Enter your choice : ";
cin >> choice;
switch (choice)
{
case 1:
BookTree.create_tree();
case 2:
BookTree.display(root);
break;
case 3:
exit(1);
default:
cout << "Wrong choice!!!" << endl;
}
}
return 0;
}
Output:
PS C:\Suraj\SPPU\Submission\DSA\Sppu-Dsa-main\Sppu-Dsa-main> g++
03BookTree.cpp -o 03BookTree.exe
PS C:\Suraj\SPPU\Submission\DSA\Sppu-Dsa-main\Sppu-Dsa-main> .\03BookTree.exe
-----Book Overview-----
Book title : Art Of Living
Chapter 1 : Ch1
Sections : A! 2 3
Chapter 2 : H2
Sections : B1
Chapter 3 : G3
Sections : C1
Chapter 4 : H4
Sections : D1
Chapter 5 : H5
Sections : E5
Chapter 6 : H6
Sections : F6
Chapter 7 : H7
Sections : G7
Chapter 8 : H8
Sections : H8
Chapter 9 : H9
Sections : I9
Chapter 10 : H10
Sections : J10
Book Tree Creation
1.Create
2.Display
3.Quit
Enter your choice : 3
PS C:\Suraj\SPPU\Submission\DSA\Sppu-Dsa-main\Sppu-Dsa-main>
Practical 04 : Implementation of Expression Tree from the given Prefix Expression.
Name : Suraj Surve
Roll no. : SA61
Code :
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int value) {
data = value;
left = nullptr;
right = nullptr;
}
};
class BST {
private:
Node* root;
public:
BST() {
root = nullptr;
}
void insert(int value) {
root = insertNode(root, value);
}
int findLongestPath() {
return findLongestPath(root);
}
int findMinimumValue() {
return findMinimumValue(root);
}
void swapPointers() {
swapPointers(root);
}
bool search(int value) {
return searchValue(root, value);
}
void display() {
displayTree(root);
cout << endl;
}
private:
Node* insertNode(Node* root, int value) {
if (root == nullptr) {
return new Node(value);
}
if (value < root->data) {
root->left = insertNode(root->left, value);
} else if (value > root->data) {
root->right = insertNode(root->right, value);
}
return root;
}
int findLongestPath(Node* root) {
if (root == nullptr) {
return 0;
}
int leftPath = findLongestPath(root->left);
int rightPath = findLongestPath(root->right);
return 1 + max(leftPath, rightPath);
}
int findMinimumValue(Node* root) {
if (root == nullptr) {
cout << "Error: Tree is empty." << endl;
return -1; // Assuming -1 represents an invalid value
}
while (root->left != nullptr) {
root = root->left;
}
return root->data;
}
void swapPointers(Node* root) {
if (root == nullptr) {
return;
}
swapPointers(root->left);
swapPointers(root->right);
Output:
PS C:\Suraj\SPPU\Submission\DSA\Sppu-Dsa-main\Sppu-Dsa-main> g++ 04_BST-
operns.cpp -o 04_BST-operns.exe
PS C:\Suraj\SPPU\Submission\DSA\Sppu-Dsa-main\Sppu-Dsa-main> .\04_BST-
operns.exe
Code:
#include <iostream>
#include <string>
using namespace std;
struct Node {
char data;
Node* left;
Node* right;
};
bool isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
Node* createNode(char data) {
Node* newNode = new Node;
newNode->data = data;
newNode->left = newNode->right = nullptr;
return newNode;
}
Node* constructExpressionTree(const string& prefixExpression, int& index) {
char c = prefixExpression[index++];
Node* newNode = createNode(c);
if (isOperator(c)) {
newNode->left = constructExpressionTree(prefixExpression, index);
newNode->right = constructExpressionTree(prefixExpression, index);
}
return newNode;
}
void postOrderTraversal(Node* root) {
Node* current = root;
Node* prev = nullptr;
string result = "";
while (current) {
if (!current->left) {
result += current->data;
current = current->right;
} else {
prev = current->left;
while (prev->right && prev->right != current) {
prev = prev->right;
}
if (!prev->right) {
prev->right = current;
current = current->left;
} else {
prev->right = nullptr;
result += current->data;
current = current->right;
}
}
}
for (int i = result.length() - 1; i >= 0; i--) {
cout << result[i] << " ";
}
}
void deleteTree(Node* root) {
if (root) {
deleteTree(root->left);
deleteTree(root->right);
delete root;
}
}
int main() {
const char* prefixExpression = "+-a*bc/def";
int index = 0;
Node* root = constructExpressionTree(prefixExpression, index);
cout << "Post-order traversal: ";
postOrderTraversal(root);
cout << endl;
deleteTree(root);
return 0;
}
Output :
PS C:\Suraj\SPPU\Submission\DSA\Sppu-Dsa-main\Sppu-Dsa-main> g++
05ExpnnTree.cpp -o 05ExpnnTree.exe
PS C:\Suraj\SPPU\Submission\DSA\Sppu-Dsa-main\Sppu-Dsa-main> .\05ExpnnTree.exe
Post-order traversal: e / d + c * b - a
PS C:\Suraj\SPPU\Submission\DSA\Sppu-Dsa-main\Sppu-Dsa-main>