0% found this document useful (0 votes)
13 views11 pages

Bubble Sort

Uploaded by

vijayaravind.p
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)
13 views11 pages

Bubble Sort

Uploaded by

vijayaravind.p
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/ 11

1.

Bubble sort
alist = eval(input("Enter a List:"))
print("Original list is",alist)
n = len(alist)
for i in range(n):
for j in range(0,n-i-1):
if alist[j] > alist[j+1]:
alist[j],alist[j+1] = alist[j+1],alist[j]
print("List after sorting ",alist)
Output
Enter a List:[12,34,32,2,4,9,6]
Original list is [12, 34, 32, 2, 4, 9, 6]
List after sorting [2, 4, 6, 9, 12, 32, 34]

2. Insertion Sort
alist = eval(input("Enter a List :"))
print("The original list :",alist)
for i in range(1,len(alist)):
key = alist[i]
j=i-1
while j >= 0 and key <alist[j]:
alist[j+1] = alist[j]
j=j-1
else:
alist[j+1] = key
print("List after sorting",alist)
Output
Enter a List :[12,56,54,43,32]
The original list : [12, 56, 54, 43, 32]
List after sorting [12, 32, 43, 54, 56]

3. Binary search
def binsearch(ar,key):
low = 0
high = len(ar) - 1
while low <= high:
mid = int((low+high) / 2)
if key == ar[mid]:
return mid
elif key < ar[mid]:
high = mid - 1
else:
low = mid + 1
else:
return - 999

ar = eval(input("Enter a sorted list"))


item = int(input("Enter the search item :"))
res = binsearch(ar , item)
if res >= 0 :
print(item , "FOUND at index",res)
else:
print("Sorry!" , item, " NOT FOUND in array ")

Output
Enter a sorted list[12,23,34,45,67,89]
Enter the search item :34
34 FOUND at index 2

Enter a sorted list[12,23,34,45,67,89]


Enter the search item :90
Sorry! 90 NOT FOUND in array

4. TEXT FILE MANIPULATION – I


file = open("sample.txt","w+")
line = eval(input("Enter some text: "))
file.writelines(line)
number_of_lines = 0
number_of_words = 0
number_of_characters = 0
file.seek(0)
for line in file:
words = line.split()
number_of_lines += 1
number_of_words += len(words)
number_of_characters += len(line)
file.close()
print("Number of lines: ", number_of_lines, "\n Number of words: ",
number_of_words,"\n Number of characters :", number_of_characters)

Output:
Enter some text: ["hai how are you","\n","hello"]
Number of lines: 2
Number of words: 5
Number of characters : 21

5. Binary file manipulation using lists.


import pickle

def insert():
file = open("student.txt","ab")
while True:
student = []
roll = int(input("Enter student Roll No:"))
sname = input("Enter student Name :")
student = [roll,sname]
pickle.dump(student,file)
choice= input("Want to add more record(y/n) :")
if(choice=='n'):
break
file.close()

def search():
roll = int(input('Enter roll that you want to search in binary file :'))
ft = open("student.txt", "rb")
new = []
try:
while True:
new = pickle.load(ft)
if new[0] == roll:
print (new)
except EOFError:
ft.close()

def mainmenu():
print (70 * '~')
print ("1......Insert")
print ("2......Search")
print (70 * '~')

choice = 'y'
while choice == 'y':
mainmenu()
print()
menu = int(input("Your choice(1..Insert,2.Search : )"))
print()
if menu == 1:
insert()
elif menu == 2:
search()
else:
print ("Please enter a valid choice...")
print()
choice = input("Do you want to do some other operations(y/n):")
print()

Output
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1......Insert
2......Search
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Your choice(1..Insert,2.Search : )1

Enter student Roll No:1001


Enter student Name :Ram
Want to add more record(y/n) :y
Enter student Roll No:1002
Enter student Name :Hari
Want to add more record(y/n) :n
Do you want to do some other operations(y/n):y

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1......Insert
2......Search
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Your choice(1..Insert,2.Search : )2

Enter roll that you want to search in binary file :1001


[1001, 'Ram']
Do you want to do some other operations(y/n):n

6. Binary file using dictionary


7. Stack implementation
def isempty(stk):
if stk == []:
return True
else:
return False

def push(stk,item):
stk.append(item)
top = len(stk) - 1

def pop(stk):
if isempty(stk):
return "Underflow"
else:
item = stk.pop()
if len(stk) == 0:
top = None
else:
top = len(stk) - 1
return item

def display(stk):
if isempty(stk):
print ("stack empty")
else:
top = len(stk) - 1
print (stk[top],"<-top")
for a in range(top - 1,-1,-1):
print (stk[a])

stack = []
top = None
while True:
print ("STACK OPERATIONS")
print ("1.Push")
print ("2.Pop")
print ("3.Display stack")
print ("4.Exit")
ch = int(input("Enter your choice(1-4):"))
if ch ==1:
item = int(input("Enter item: "))
push(stack,item)
elif ch == 2:
item = pop(stack)
if item == "Underflow":
print ("Underflow ! Stack is empty! ")
else:
print ("Popped item is",item)
elif ch == 3:
display(stack)
elif ch == 4:
break
else:
print ("Invalid choice!")

Output
STACK OPERATIONS
1.Push
2.Pop
3.Display stack
4.Exit
Enter your choice(1-4):1
Enter item: 12
STACK OPERATIONS
1.Push
2.Pop
3.Display stack
4.Exit
Enter your choice(1-4):1
Enter item: 13
STACK OPERATIONS
1.Push
2.Pop
3.Display stack
4.Exit
Enter your choice(1-4):3
13 <-top
12
STACK OPERATIONS
1.Push
2.Pop
3.Display stack
4.Exit
Enter your choice(1-4):2
Popped item is 13
STACK OPERATIONS
1.Push
2.Pop
3.Display stack
4.Exit
Enter your choice(1-4):3
12 <-top
STACK OPERATIONS
1.Push
2.Pop
3.Display stack
4.Exit
Enter your choice(1-4):4

8. CSV manipulation
import csv
fields = ['Name', 'Branch', 'Year', 'CGPA']
rows = [ ['Nikhil', 'COE', '2', '9.0'],
['Sanchit', 'COE', '2', '9.1'],
['Aditya', 'IT', '2', '9.3'],
['Sagar', 'SE', '1', '9.5'],
['Prateek', 'MCE', '3', '7.8'],
['Sahil', 'EP', '2', '9.1']]
filename = "university_records.csv"
with open(filename, 'w') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(fields)
csvwriter.writerows(rows)
filename = "university_records.csv"
fields = []
rows = []
with open(filename, 'r') as csvfile:
csvreader = csv.reader(csvfile)
fields = next(csvreader)
for row in csvreader:
rows.append(row)
print ("The column headers are....")
print (fields)
for row in rows:
for col in row:
print('{:<10}'.format(col),end = " ")
print()

Output
The column headers are....
['Name', 'Branch', 'Year', 'CGPA']
Nikhil COE 2 9.0
Sanchit COE 2 9.1
Aditya IT 2 9.3
Sagar SE 1 9.5
Prateek MCE 3 7.8
Sahil EP 2 9.1

SQL
Create the following tables Product and Client. Write SQL commands for the given statements.

PRODUCT
P_ID ProductName Manufacturer Price
TP01 Talcum Powder LAK 40
FW05 Face Wash ABC 45
BS01 Bath Soap ABC 55
SH06 Shampoo XYZ 120
FW12 Face Wash XYZ 95

CLIENT
C_ID Client Name City P_ID
01 Cosmetic Shop Delhi FW05
06 Total Health Mumbai BS01
12 Live Life Delhi SH06
15 Pretty Woman Delhi FW12
16 Dreams Bangalore TP01

1. To display the details of those clients whose city is Delhi.


Ans: Select * from product where city = “Delhi”;
2. To display the details of Products whose Price is in the range of 15 to 100.(Both
values included)
Ans: Select * from product where price between 15 and 100;
3. To display product name and client name from product and CLIENT.
Ans: Select productname , clientname from product , client where product.p_id = client.p_id;
4. To display the maximum and minimum price for each manufacturer.
Ans: Select manufacturer, max(price),min(price) from product group by manufacturer;

Create the tables ITEM and CUSTOMER. Write SQL Commands for the given statements
ITEM
I_ID ItemName Manufacture Price
PC01 Personal Computer ABC 35000
LC05 Laptop ABC 55000
PC03 Personal Computer XYZ 32000
PC06 Personal Computer COMP 37000
LC03 Laptop PQR 57000

CUSTOMER

C_ID CustomerName City l_ID


01 REKHA Delhi LC03
06 MANSH Mumbai PC03
12 RAJEEV Delhi PC06
15 YAJNESH Delhi LC03
16 VIJAY Bangalore PC01

1. To display the details of those customers whose city is Delhi.


Ans: Select * from customer where city = “delhi”;
2. To display the details of item whose price is in the range of 35000 to 55000 ( both values
included)
Ans: Select * from item where price between 35000 and 55000;
3. To display the customer name, city from table Customer and ItemName,price from table
Item with their corresponding matching I_ID.
Ans: Select customername, city, itemname, price from customer, item where
customer.c_id = item.c_id;
4. To display the item name and price as price *100 where manufacturer is ABC.
Ans: Select itemname, price*100 price from item where manufacture = “ABC”;

You might also like