0% found this document useful (0 votes)
10 views6 pages

Ds

The document contains several code snippets for different functionalities, including a shopping basket system, linked list operations, a phone directory, bubble sort for student grades, and a weighted graph for finding the shortest path. Each section provides methods for adding, searching, and deleting items or contacts, as well as sorting and graph traversal algorithms. The code is structured to allow user interaction through menus and inputs.

Uploaded by

thyra
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)
10 views6 pages

Ds

The document contains several code snippets for different functionalities, including a shopping basket system, linked list operations, a phone directory, bubble sort for student grades, and a weighted graph for finding the shortest path. Each section provides methods for adding, searching, and deleting items or contacts, as well as sorting and graph traversal algorithms. The code is structured to allow user interaction through menus and inputs.

Uploaded by

thyra
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/ 6

1..

product=[] total=0

price=[] print("Item le in basket : ")

total=0 for item in product:

popped_total=0 print(item)

while(True) : for amount in price:

item=input("Enter name (q to quit) : ") total=total+amount

if(item=="q") : print("amount le for item in basket : ",total)

break

else :

product.append(item)

amount=int(input("Enter a price : "))

price.append(amount)

total=total+amount

product.reverse()

print("Your list names : ")

x=len(product)

for item in product :

print(item)

print("Tot amount : ",total)

n=int(input("Enter no of items to pop : "))

product.reverse()

for item in product :

if((len(product)-n)==x):

break

else:

print("pop item is : ",product[len(product)-1])

print("price : ",price[len(price)-1])

popped_total=popped_total+price[len(price)-1]

product.pop()

price.pop()

print("amount : ",popped_total)
2… class Node: if not head:

def __init__(self, data): return None

self.data = data return head.next

self.next = None def delete_at_last(head):

def insert_at_first(head, data): if not head or not head.next:

new_node = Node(data) return None

new_node.next = head current = head

return new_node while current.next and current.next.next:

def insert_at_last(head, data): current = current.next

new_node = Node(data) current.next = None

if not head: return head

return new_node def delete_in_middle(head, posi on):

current = head if not head or posi on == 0:

while current.next: return head.next

current = current.next current = head

current.next = new_node for _ in range(posi on - 1):

return head if not current.next:

def insert_in_middle(head, data, posi on): return head

new_node = Node(data) current = current.next

if not head or posi on == 0: if not current.next:

new_node.next = head return head

return new_node current.next = current.next.next

current = head return head

for _ in range(posi on - 1): def search(head, key):

if not current.next: current = head

break posi on = 0

current = current.next while current:

new_node.next = current.next if current.data == key:

current.next = new_node return posi on

return head current = current.next

def delete_at_first(head): posi on += 1


return -1 elif choice == 4:

def display_list(head): head = delete_at_first(head)

current = head elif choice == 5:

while current: head = delete_at_last(head)

print(current.data) elif choice == 6:

print() posi on = int(input("Enter posi on to delete: "))

current = current.next head = delete_in_middle(head, posi on)

# Driver code elif choice == 7:

head = None key = input("Enter name to search: ")

while True: posi on = search(head, key)

print("\nMenu:") if posi on != -1:

print("1. Insert at first") print(f"Passenger found at posi on: {posi on}")

print("2. Insert at last") else:

print("3. Insert in Middle") print("Passenger not found")

print("4. Delete at first") elif choice == 8:

print("5. Delete at last") display_list(head)

print("6. Delete in Middle") elif choice == 9:

print("7. Search") break

print("8. Display") else:

print("9. Exit") print("Invalid choice, please try again.")

choice = int(input("Enter your choice: "))

if choice == 1:

data = input("Enter name to insert at beginning: ")

head = insert_at_first(head, data)

elif choice == 2:

data = input("Enter name to insert at end: ")

head = insert_at_last(head, data)

elif choice == 3:

data = input("Enter name to insert in middle: ")

posi on = int(input("Enter posi on to insert: "))

head = insert_in_middle(head, data, posi on)


3… phone_directory = {} phone_number = input("Enter phone number: ")

def add_contact(name, phone_number): add_contact(name, phone_number)

phone_directory[name] = phone_number print("number added successfully!")

def search_contact(name): elif choice == "2":

if name in phone_directory: name = input("Enter the name to search: ")

return phone_directory[name] result = search_contact(name)

else: print("Phone number:", result)

return "Contact not found" elif choice == "3":

def remove_contact(name): display_directory()

if name in phone_directory: elif choice == "4":

del phone_directory[name] name = input("Enter the name to remove: ")

print("number removed successfully!") remove_contact(name)

else: elif choice == "5":

print("Contact not found") break

def display_directory(): else:

if not phone_directory: print("Invalid choice. Please try again.")

print("directory is empty.")

else:

print("Phone Directory:")

for name, phone_number in phone_directory.items():

print(f"{name}: {phone_number}")

while True:

print("Phone Directory Menu:")

print("1.create new contact")

print("2.Search for a contact")

print("3.Display directory")

print("4.Remove a contact")

print("5.Exit")

choice = input("Enter choice: ")

if choice == "1":

name = input("Enter the name: ")


4… def bubble_sort(grades): 5… import hashlib

n = len(grades) document = input("Enter the document you want to sign: ")

for i in range(n): private_key = input("Enter your private key: ")

swapped = False document_hash = hashlib.sha256(document.encode()).hexdigest()

for j in range(0, n - i - 1): signature = document_hash + private_key

if grades[j][1] < grades[j+1][1]: print("Document signed. Signature:", signature)

grades[j], grades[j+1] = grades[j+1], grades[j] document_to_verify = input("Enter the document for verifica on: ")

swapped = True private_key_for_verifica on = input("Enter the private key for verifica on: ")

if not swapped: verifica on_hash = hashlib.sha256(document_to_verify.encode()).hexdigest()

break expected_signature = verifica on_hash + private_key_for_verifica on

def sort_student_grades(): if expected_signature == signature:

student_grades = [] print("Signature is valid.")

num_students = int(input("Enter the number of students: ")) else:

for _ in range(num_students): print("Signature is invalid.")

name = input("Enter student name: ")

grade = int(input(f"Enter grade for {name}: "))

student_grades.append((name, grade))

bubble_sort(student_grades)

print("\nSorted student grades:")

for name, grade in student_grades:

print(f"{name}: {grade}")

if __name__ == "__main__":

sort_student_grades()
6… import heapq current = end_node

class WeightedGraph: while current is not None:

def __init__(self): path.append(current)

self.graph = {} current = previous_nodes.get(current)

def add_edge(self, node1, node2, weight): return path[::-1]

if node1 not in self.graph: def main():

self.graph[node1] = [] g = WeightedGraph()

if node2 not in self.graph: g.add_edge("home", "store", 3)

self.graph[node2] = [] g.add_edge("store", "medical",2)

self.graph[node1].append((node2, weight)) g.add_edge("home", "atm", 10)

self.graph[node2].append((node1, weight)) g.add_edge("atm", "bank", 2)

def start(self, start_node): g.add_edge("medical", "temple", 4)

if start_node not in self.graph: g.add_edge("temple", "park", 1)

return None, None g.add_edge("park", "mall", 7)

distances = {node: float('inf') for node in self.graph} g.add_edge("home", "", 13)

distances[start_node] = 0 start = input("star ng node: ")

priority_queue = [(0, start_node)] end = input("des na on node: ")

previous_nodes = {node: None for node in self.graph} distances, previous_nodes = g.start(start)

while priority_queue: if end in distances:

current_distance, current_node = heapq.heappop(priority_queue) path = g.get_shortest_path(previous_nodes, end)

if current_distance > distances[current_node]: distance = distances[end]

con nue print(f"Shortest path from {start} to {end}: {' -> '.join(path)}, Distance: {distance} KM")

for neighbor, weight in self.graph[current_node]: else:

distance = current_distance + weight print(f"No path found {start} to {end}.")

if distance < distances[neighbor]: if __name__ == "__main__":

distances[neighbor] = distance main()

heapq.heappush(priority_queue, (distance, neighbor))

previous_nodes[neighbor] = current_node

return distances, previous_nodes

def get_shortest_path(self, previous_nodes, end_node):

path = []

You might also like