Hi
def insertion_sort(list):
for index in range(1,len(list)):
value=list[index]
i=index-1
while i>=0:
if value<list[i]:
list[i+1]=list[i] #shift number in slot i right to slot i+1
list[i]=value #shift value left into slot i
i-=1
else:
break
n=int(input("Enter the number of elements in the list : "))
l=list()
for i in range(n):
num=int(input(f"Enter element {i} : "))
l.append(num)
insertion_sort(l)
print(f"The sorted list is {l}")
def binary_search(list,element):
list.sort()
top=len(list)-1
bottom=0
while top>=bottom:
mid=(top+bottom)//2
if element==list[mid]:
return mid
elif element<list[mid]:
top = mid-1
elif element>list[mid]:
bottom=mid+1
return -1
n=int(input("Enter the number of elements of the list : "))
l=list()
for i in range(n):
num=int(input(f"Enter element {i} of the list : "))
l.append(num)
key=int(input("Enter the value to be searched in the list : "))
pos = binary_search(l,key)
if pos!=-1:
print(f"The element is present at the index {pos}")
else:
print("The element is not present in the list")
student_dict = dict()
while True:
print("1. Insert ")
print("2. Delete ")
print("3. Search ")
print("4. Exit \n")
a = int(input("Please choose a number to proceed : "))
if a == 1:
roll_num = input("Please enter the roll number to insert : ")
if roll_num in student_dict:
print("Data already found!!")
else:
student_dict[roll_num] = []
name = input("Please enter the name corresponding to the roll no : ")
cgpa = float(input("Please enter the cgpa corresponding to the roll no : "))
ph_no = int(input("Please enter the phone number corresponding to the roll no : "))
student_dict[roll_num].append(name)
student_dict[roll_num].append(cgpa)
student_dict[roll_num].append(ph_no)
print("Successfully inserted!!!")
print("The info present in the dictionary are : ")
print(student_dict)
if a == 2:
delete = input("Please enter which roll no you want to delete : ")
student_dict.pop(delete)
print("Successfully deleted!!!")
print(student_dict)
if a == 3:
search = input("Please enter the roll no to be searched : ")
if search in student_dict:
print("Data found !!!")
print(student_dict[search])
else:
print("No data found!!")
if a == 4:
print("Thank you!!!")
break
sample = set()
while True:
print("1. Create empty set ")
print("2. Insert ")
print("3. Delete ")
print("4. Search ")
print("5. Print ")
print("6. Union ")
print("7. Intersection ")
print("8. Set difference ")
print("9. Symmetric difference ")
print("10. Exit ")
a = int(input("Please choose a number to proceed : "))
if a == 1:
empty_s = set()
print("Empty set created!!")
print(empty_s)
if a == 2:
val = (input("Please enter the elements to be inserted : "))
if val in sample:
print("The value already exists")
else:
sample.add(val)
print("Value inserted !!")
print(sample)
if a == 3:
val1 = input("Please enter which element has to be deleted : ")
if val1 in sample:
sample.remove(val1)
else:
print("No element found to delete")
if a == 4:
sear = input("please enter the element to be searched : ")
if sear in sample:
print("element found")
else:
print("No element found")
if a == 5:
print("The set is : ")
print(sample)
if a == 6:
sample3 = set()
siz = int(input("Please enter how many elements to be added : "))
for i in range(0, siz):
val3 = input("Please enter the element : ")
sample3.add(val3)
print("The union of the first and the recent set is : ")
un = sample.union(sample3)
print("The final set is : ")
print(un)
if a == 7:
sample4 = set()
siz = int(input("Please enter how many elements to be added : "))
for i in range(0, siz):
val3 = input("Please enter the element : ")
sample4.add(val3)
print("The union of the first and the recent set is : ")
un1 = sample.intersection(sample4)
print("The final set is : ")
print(un1)
if a == 8:
sample4 = set()
siz = int(input("Please enter how many elements to be added : "))
for i in range(0, siz):
val3 = input("Please enter the element : ")
sample4.add(val3)
print("The union of the first and the recent set is : ")
un2 = sample.difference(sample4)
print("The final set is : ")
print(un2)
if a == 9:
sample5 = set()
siz = int(input("Please enter how many elements to be added : "))
for i in range(0, siz):
val3 = input("Please enter the element : ")
sample5.add(val3)
print("The union of the first and the recent set is : ")
un3 = sample.symmetric_difference(sample5)
print("The final set is : ")
print(un3)
if a == 10:
print("Thank you")
break
class Node:
def init(self, data):
self.data = data
self.next = None
class stack:
def init(self, data=None):
self.top = None
if data:
self.Push(data)
def is_Empty(self):
if self.top == None:
return True
else:
return False
def Push(self, data):
node = Node(data)
if self.top == None:
self.top = node
else:
node.next = self.top
self.top = node
def pop(self):
if self.top == False:
return "Empty stack!!"
else:
node = self.top
self.top = node.next
node.next = None
data = node.data
del node
return f'Popped: {data}'
def peek_element(self):
if self.top != None:
print(self.top)
return self.top.data
else:
return 0
def display(self):
if self.top == None:
print("Empty")
else:
temp = self.top
while temp != None:
print(temp.data, "address = ", temp.next)
temp = temp.next
print()
a = stack()
while(1):
print(" 1.Push\n 2.Pop\n 3.Peek\n 4.Display\n 5.Exit\n")
choice = int(input("Please enter your choice to proceed : "))
if choice == 1:
val = input("Please enter the elements to insert inside stack : \n")
a.Push(val)
print("Successfully inserted!!!")
elif choice == 2:
a.pop()
print("successfully popped !!!")
elif choice == 3:
print("The peak element is : ", a.peek_element())
elif choice == 4:
a.display()
elif choice == 5:
break
class Node(object):
def init(self, x):
self.data = x
self.NextNode = None
class Queue(object):
def init(self):
self.front = None
self.rear = None
def enqueue(self, x):
NewNode = Node(x)
if (self.front is None):
NewNode.NextNode = self.front
self.front = NewNode
self.rear = self.front
else:
self.rear.NextNode = NewNode
self.rear = NewNode
print("\nSuccesfully inserted in Queue\n")
def dequeue(self):
if (self.front is not None):
if (self.front == self.rear):
temp = self.front
self.front = self.front.NextNode
self.rear = self.front
var = temp.data
del temp
return var
else:
temp = self.front
self.front = self.front.NextNode
var = temp.data
del temp
return var
else:
return None
def peek(self):
if (self.front is not None):
temp = self.front
return temp.data
else:
return None
def print(self):
if (self.front is not None):
print("\nThe elements in Queue are: ")
temp = self.front
while (temp is not None):
print(temp.data, '\taddress=', temp.NextNode)
temp = temp.NextNode
else:
print("\nQueue is Empty\n")
Queue1 = Queue()
ch = 1
while (ch != 5):
print("1.Enqueue \n2.Dequeue \n3.Peek \n4.Print \n5.Exit")
ch = int(input("Enter your choice: "))
if (ch == 1):
n = int(input("Enter the element: "))
Queue1.enqueue(n)
elif ch == 2:
temp = Queue1.dequeue()
if (temp is not None):
print("\nThe popped value is: ", temp)
else:
print("\nunderflow\n")
elif ch == 3:
temp = Queue1.peek()
if (temp is not None):
print("\nThe peek value is: ", temp)
else:
print("\nQueue is Empty\n")
elif ch == 4:
Queue1.print()
elif ch == 5:
break
else:
print("\nwrong choice, try again \n")
'''
To implement linked list using references
x=[1,2,3] # x is the refenrece for [1,2,3]
print(x)
y=x # y is the reference of x
print(y)
y.append(89)
print(y)
print(x)
'''
Implementation of List ADT
class Node(object):
def init(self, x):
self.data=x
self.NextNode=None
class LinkedList(object):
def init(self):
self.Hnode=None
def Insert(self, x, i):
NewNode=Node(x)
if(i is 1):
NewNode.NextNode=self.Hnode #link1
self.Hnode=NewNode #link2
else:
pos=1
tnode=self.Hnode
while((tnode is not None) and(pos<i-1)):
pos=pos+1
tnode=tnode.NextNode
temp=tnode.NextNode # temp is the ref of ith node
tnode.NextNode=NewNode # the Next Node in (i-1)th node becomes reference of newly crated node
NewNode.NextNode=temp #temp is ith node before inserstion
def Delete(self, n):
tnode=self.Hnode
if(n==1):
dnode=self.Hnode
self.Hnode=self.Hnode.NextNode
else:
i=1
while( (tnode is not None) and (i<n-1) ):
i=i+1
tnode=tnode.NextNode
#tnode is refering to n-1th node
dnode=tnode.NextNode # dnode is refering to nth node
tnode.NextNode=dnode.NextNode
del dnode # OS will include space allotted for dnode into free memory
def Search(self, x):
tnode=self.Hnode
while((tnode is not None) and (tnode.data is not x)):
tnode=tnode.NextNode
if(tnode is not None):
print("yes")
else:
print("No")
def PrintList(self):
print(self.Hnode)
tnode=self.Hnode
while(tnode is not None):
print(tnode.data)
tnode=tnode.NextNode
List1 = LinkedList() # List1 represents empty list
'''
n1=Node(89)
List1.Hnode=n1 #
#print(List1.Hnode.data)
n2=Node(11)
n1.NextNode=n2
n3=Node(17)
n2.NextNode=n3
'''
List1.Insert(21, 1)
List1.Insert(13,1)
List1.Insert(27,3)
List1.Insert(17, 2)
List1.PrintList()
List1.Delete(2)
List1.PrintList()
#List1.Search(270)
import pickle
file1 = open("Library.dat", 'wb')
file1.close()
def WriteFile():
libDict = {}
file1 = open("Library.dat", 'ab')
while(1):
bookTitle = input("Enter the Book Title: ")
IISN = input("Enter the IISN: ")
price = int(input("Enter the price: "))
edition = int(input("Enter the book edition: "))
year = int(input("Enter the year of publication: "))
author = input("Enter the author name: ")
x = [IISN, price, edition, year, author]
libDict[bookTitle] = x
opt = int(input("Press 1 for more entries, 0 to end: "))
if(opt == 0):
break
pickle.dump(libDict, file1)
file1.close()
def ReadFile():
file1 = open("Library.dat", 'rb')
while(1):
try:
x = pickle.load(file1)
print(x)
except EOFError:
print("\n\nEnd of File")
break
file1.close()
def SearchFile():
file1 = open("Library.dat", 'rb')
key = input("Enter the book title to search: ")
while(1):
try:
x = pickle.load(file1)
if key in x.keys():
print("\n------BOOK FOUND-------\n")
for keys, values in x.items():
if keys == key:
lis = values
print("BOOK ISSN : ", lis[0],"\nBOOK PRICE : ",lis[1],"\nBOOK EDITION : ",lis[2],"\nYEAR : ",lis[3],"\nAUTHOR :",lis[4])
else:
print("Book not found!")
except EOFError:
print("\n\nEnd of File")
break
file1.close()
while(1):
opt = int(input("Select from the following:\n1. Write\n2.Read\n3. Search\n4 .Exit\nYour Choice: "))
if opt==1:
WriteFile()
elif opt==2:
ReadFile()
elif opt==3:
SearchFile()
elif opt==4:
print("Exiting...")
exit()
else:
print("Invalid option, Try again!\n")
import numpy
def SumofTrglr(matrix):
p, q = 0, 0
upper_triangular_sum = 0
lower_triangular_sum = 0
for p in range(len(matrix)):
for q in range(len(matrix[0])):
if (p <= q):
upper_triangular_sum += matrix[p][q]
for p in range(len(matrix)):
for q in range(len(matrix[0])):
if (q <= p):
lower_triangular_sum += matrix[p][q]
return upper_triangular_sum - lower_triangular_sum
def Matrix_ipt():
rows = int(input("Enter the number of rows you want in the matrix: "))
columns = int(input("Enter the number of columns you want in the matrix: "))
A = []
for p in range(rows):
row = input(f"Enter the elements of row {p+1}: ")
A.append([int(a) for a in row.split()])
return A
while True:
print("1.Matrix Addition")
print("2.Matrix Subtraction")
print("3.Scalar Matrix Multiplication")
print("4.Elementwise Matrix Multiplication")
print("5.Matrix Multiplication")
print("6.Matrix Transpose")
print("7.Trace of a Matrix")
print("8.Solve System of Linear Equations")
print("9.Determinant")
print("10.Inverse")
print("11.Singular Value Decomposition")
print("12.Eigen Value")
print("13.Search an Element")
print("14.Sum of Difference of Upper and Lower Triangular Matrix")
print("15.Exit")
opt = int(input("Enter your choice: "))
if (opt == 1):
print("Performing Matrix Addition")
A = Matrix_ipt()
B = Matrix_ipt()
print(np.add(A, B))
elif (opt == 2):
print("Performing Matrix Subtraction")
A = Matrix_ipt()
B = Matrix_ipt()
print(np.subtract(A, B))
elif (opt == 3):
print("Performing Scalar Matrix Multiplication")
A = Matrix_ipt()
val = int(input("Enter the scalar: "))
print(np.multiply(A, val))
elif (opt == 4):
print("Performing Elementwise Matrix Multiplication")
A = Matrix_ipt()
B = Matrix_ipt()
print(np.multiply(A, B))
elif (opt == 5):
print("Performing Matrix Multiplication")
A = Matrix_ipt()
B = Matrix_ipt()
print(np.dot(A, B))
elif (opt == 6):
print("Performing Matrix Transpose")
A = Matrix_ipt()
print(np.transpose(A))
elif (opt == 7):
print("Finding Trace of a Matrix")
A = Matrix_ipt()
print(np.trace(A))
elif (opt == 8):
print("Solving System of Linear Equations")
A = Matrix_ipt()
B = Matrix_ipt()
print(np.linalg.solve(A, B))
elif (opt == 9):
print("Calculating Determinant Of A Matrix")
A = Matrix_ipt()
print(np.linalg.det(A))
elif (opt == 10):
print("Inverse Of A Matrix")
A = Matrix_ipt()
print(np.linalg.inv(A))
elif (opt == 11):
print("Singular Value Decomposition")
A = Matrix_ipt()
print(np.linalg.svd(A))
elif (opt == 12):
print("Determining Eigen Value")
A = Matrix_ipt()
print(np.linalg.eig(A))
elif (opt == 13):
print("Search an Element")
A = Matrix_ipt()
elmt = int(input("Enter element: "))
print(np.where(A == elmt))
elif (opt == 14):
print("Finding Difference of Sum of Upper and Lower Triangular Matrix")
A = Matrix_ipt()
print(SumofTrglr(A))
elif (opt == 15):
break
else:
print("You have made an invalid choice")
input("Press Enter to continue...")
import pandas as pd
import os
import sys
def get_index(accno):
df = pd.read_csv("bank.csv")
return df[df["Account Number"] == accno].index[0]
def append():
df = pd.read_csv("bank.csv")
dff = pd.read_csv("contact.csv")
name = input("Enter the name of the account holder: ")
accno = int(input("Enter the account number: "))
print("Enter the account type:")
print("1. Savings")
print("2. Current")
ch = int(input("Enter your choice: "))
if ch == 1:
acctype = "Savings"
elif ch == 2:
acctype = "Current"
else:
acctype = "Savings"
adhaar = int(input("Enter the adhaar number: "))
balance = int(input("Enter the balance: "))
contact = int(input("Enter the contact number: "))
dob = input("Enter the date of birth: ")
address = input("Enter the address: ")
df.loc[len(df)] = [name, accno, acctype, adhaar, balance]
dff.loc[len(dff)] = [name, adhaar, contact, dob, address]
df.to_csv("bank.csv", index=False)
dff.to_csv("contact.csv", index=False)
print("Record appended successfully")
def delete():
df = pd.read_csv("bank.csv")
accno = int(input("Enter the account number: "))
df = df[df["Account Number"] != accno]
df.to_csv("bank.csv", index=False)
print("Record deleted successfully")
def credit():
df = pd.read_csv("bank.csv")
accno = int(input("Enter the account number: "))
amount = int(input("Enter the amount to be credited: "))
df.loc[get_index(accno), "Balance"] += amount
df.to_csv("bank.csv", index=False)
print("Amount credited successfully")
def debit():
df = pd.read_csv("bank.csv")
accno = int(input("Enter the account number: "))
amount = int(input("Enter the amount to be debited: "))
df.loc[get_index(accno), "Balance"] -= amount
if (df.loc[get_index(accno), "Balance"] < 0 and df.loc[get_index(accno), "Account Type"] == "Savings"):
print("Insufficient balance")
return
df.to_csv("bank.csv", index=False)
print("Amount debited successfully")
def display():
df = pd.read_csv("bank.csv")
accno = int(input("Enter the account number: "))
print(df[df["Account Number"] == accno])
if not os.path.exists("bank.csv"):
df = pd.DataFrame(
columns=["Name", "Account Number", "Account Type", "Adhaar Number", "Balance"])
df.to_csv("bank.csv", index=False)
if not os.path.exists("contact.csv"):
df = pd.DataFrame(
columns=["Name", "Adhaar Number", "Contact Number", "DOB", "Address"])
df.to_csv("contact.csv", index=False)
while True:
os.system("clear")
print("1. Append record")
print("2. Delete record")
print("3. Credit")
print("4. Debit")
print("5. Display account details")
print("6. Merge tables")
print("7. Exit")
ch = int(input("Enter your choice: "))
os.system("clear")
if ch == 1:
append()
elif ch == 2:
delete()
elif ch == 3:
credit()
elif ch == 4:
debit()
elif ch == 5:
display()
elif ch == 6:
df = pd.read_csv("bank.csv")
dff = pd.read_csv("contact.csv")
df = pd.merge(df, dff, on=["Name", "Adhaar Number"])
df.to_csv("merge.csv", index=False)
print("Tables merged successfully")
elif ch == 7:
sys.exit()
else:
print("Invalid choice")
input("\nPress enter to continue")
import pandas as pd
names = ["Ram", "Sam", "Prabahu"]
ac_nos = ['9893893891', '9893893898', '9893893871']
ac_types = ['SB', 'CA', 'SB']
adhar_no = ['959389389173', '959389389179', '959389389159']
balance = [8989839, 7690990, 989330]
d = {"Name": names, "AccountNo": ac_nos, "AccountType": ac_types,
"AadharNo": adhar_no, "balance": balance}
df1 = pd.DataFrame(d)
print(df1)
converting to csv type
df1.to_csv("SBIAccountHolder.csv")
while 1:
ch = int(input(
"Enter choice 1)Append row 2)Delete row 3)Credit 4)Debit 5)Account Details 6)Exit :"))
if ch == 1:
print("Enter data to append : ")
name = input("Name:")
acno = input("AccountNo:")
acty = input("AccountType:")
adno = input("Aadhaar Number:")
bal = input("Balance:")
names.append(name)
ac_nos.append(acno)
ac_types.append(acty)
adhar_no.append(adno)
balance.append(bal)
d = {"Name": names, "AccountNo": ac_nos, "AccountType": ac_types,
"AadharNo": adhar_no, "balance": balance}
df1 = pd.DataFrame(d)
df1.to_csv("SBIAccountHolder.csv")
# df1.append(df2)
print(df1)
elif ch == 2:
acno = input("enter account number to delete record:")
# x = df1.loc[df1['AccountNo'] == acno, 'Name'].iloc[0]
# df1.drop(int(x), inplace=True)
df_index = df1.set_index('AccountNo')
df_index = df_index.drop(acno)
df1 = df_index
print(df_index)
df_index.to_csv("SBIAccountHolder.csv")
elif ch == 3:
acno = input("enter account number to credit:")
amt = int(input("ENter amount to credit :"))
df1.loc[df1['AccountNo'] == acno,
'balance'] = df1.loc[df1['AccountNo'] == acno, 'balance'] + amt
# x = x+amt
print(df1)
df1.to_csv("SBIAccountHolder.csv")
elif ch == 4:
acno = input("enter account number to Debit:")
amt = int(input("ENter amount to Debit :"))
if (df1.loc[df1['AccountNo'] == acno, 'AccountType'].iloc[0] == 'SB'):
if ((df1.loc[df1['AccountNo'] == acno, 'balance']).tolist())[0] < amt:
print("Insuffient Balance!")
continue
df1.loc[df1['AccountNo'] == acno,
'balance'] = df1.loc[df1['AccountNo'] == acno, 'balance'] - amt
# x = x+amt
print(df1)
df1.to_csv("SBIAccountHolder.csv")
elif ch == 5:
print(df1)
elif ch == 6:
print("Exiting!")
break
else:
print("Enter valid choice!")