0% found this document useful (0 votes)
200 views37 pages

CBSE Practicals

The document describes Python functions and code to: 1) Read and write to text files, displaying content and appending lines. It also finds word frequencies. 2) Create a new file containing words from a source file that don't start with vowels. 3) Read a file of student data stored as tuples, sort and display the data in various ways.

Uploaded by

Divyank Maan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
200 views37 pages

CBSE Practicals

The document describes Python functions and code to: 1) Read and write to text files, displaying content and appending lines. It also finds word frequencies. 2) Create a new file containing words from a source file that don't start with vowels. 3) Read a file of student data stored as tuples, sort and display the data in various ways.

Uploaded by

Divyank Maan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

11/30/2020 DhruvKikan.

ipynb - Colaboratory

1)
Write a function to create a text file containing following
data: Neither apple nor pine are in pineapple. Boxing rings
are square.
Writers write, but fingers don’t fing. Overlook and oversee are
opposites. A house can burn up as it burns down. An alarm goes off
by going on.
a) Read back the entire file content using read( ) or readlines( ) and display
on the screen.
b) Append more text of your choice in the file and display the content of
file with line numbers prefixed to line.
c) Display last line of file.
d) Display first line from 10th character onwards.
e) Read and display a line from the file. Ask user to provide the line
number to be read.
f) Find the frequency of words beginning with every
letter i.e. (for the above example)
Words beginning with a:
5 Words beginning with
n: 2 Words beginning
with p: 2
Words beginning with o: 5 and so on

# Part a) start
def function():
k=open('Pracl','w')
k.writelines(”Neither apple or pine are in pineapple. Boxing rings are square.\
nWriters
k=open( ' Prac1' )
r=k. read( )
print(r)
function()
# Part a) finished

Neither apple or pine are in pineapple. Boxing rings are square.


Writers write, but fingers don't fing. Overlook and oversee are
opposites. A house can burn up as it burns down. An alarm goes off
by going on.

# Part b) start
k=open('Pracl','a')
k.write('\nSticks and stones may break your bones.')
k=open('Prac1')
r=k.readlines()
for a in
range(len(r)):
print(a+1,r[a])
# Part b) finished

1 Neither apple or pine are in pineapple. Boxing rings are square.

2 Writers write, but fingers don't fing. Overlook and oversee are opposites.

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 1/
11/30/2020 DhruvKikan.ipynb - Colaboratory
3 A house can burn up as it burns down. An alarm goes off by going on.

4 Sticks and stones may break your bones.

# Part c) start

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 2/
11/30/2020 DhruvKikan.ipynb - Colaboratory
r=opeuy rraci , r
; r=k.readlines()
print(r[len(r)-1])
# Part c)
finished

Sticks and stones may break your bones.

# Part d) start
k=open('Pracl','r')
k.seek(10)
r=k.readline()
print(r)
# Part d) finished

ple or pine are in pineapple. Boxing rings are square.

# Part e)
start def
read(1):
k=open('Pracl','r')
r=k.readlines()
print(r[l])
l=int(input('Enter the line num:
')) read(1-1)
# Part e) finished

Enter the line num: 2


Writers write, but fingers don't fing. Overlook and oversee are opposites.

# Part f) start
k=open('Prac1','r')
r=k.read()
d={}
for a in
r:
d[a]=0
for a in
r: d[a]
+=1
print(d)
# Part f) finished

{'N': 1, 'e': 23, 'i': 14, 't': 9, 'h': 2, 'r': 18, ' ': 41, 'a': 14, 'p': 9,
'l': 4

2)
Assume that a text file named file1.txt contains some text, write a function named
isvowel( ) that reads the file file1.txt and creates a new file named file2.txt,
which sha contain only those words from the file file1.txt which don’t start with a
https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 3/
11/30/2020 DhruvKikan.ipynb - Colaboratory
vowel
For example, if the file1.txt
contains: Carry Umbrella and Overcoat
When it Rains Then the file file2.txt
shall contain Carry When Rains

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 4/
11/30/2020 DhruvKikan.ipynb - Colaboratory

a=open('filel.txt','w')
a.write('do not Carry Umbrella and Overcoat When it does not
Rain') a.close()
def isvovel(a):
b=open('file2.txt','w')
vovellst=[65,69,73,79,85,97,101,105,111,117]
w=a.read()
k=w.split()
for y in
k:
if ord(y[0]) in
vovellst: pass
else:
b.write(y+' ')
b.close()
b=open('file2.txt','r')
c=b.read()
print('Contents of file1: do not Carry Umbrella and Overcoat When it does not
Rain') print('Contents of file2:',c)
a=open('filel.txt','r')
x=isvovel(a)

Contents of filel: do not Carry Umbrella and Overcoat When it does not
Rain Contents of file2: do not Carry When does not Rain

3)
A file containing data about a collection of students has the following
format. Rajat Sen 12345 1 CSEE
Jagat Narain 13467 3 CSEE
Anu Sharma 11756 2 Biology
SumitaTrikha 23451 4 Biology
SumderKumra 11234 3 MME
KantiBhushan 23211 3 CSEE
Each line contains a first name, a last name, a registration number, no of years
and a department separated by tabs.

a) Write a Python program that will copy the contents of the file into a list of
tuples
b) Display:
1) The full details of the student sorted by registration number
2) The names of all students with no of year less than 3
3) The number of people in each department

op=open('tuplewriter.txt','w')
op.writelines(”Rajat Sen 12345 1 CSEE \nJagat Narain 13467 3 CSEE \nAnu Sharma
11756 2 Bio op.close()
# Part a) start
op=open('tuplewriter.txt','r')
a=op.readlines()
lst=[]
for x in a:
q=x.split()
lst.append(tuple(q))

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 5/
11/30/2020 DhruvKikan.ipynb - Colaboratory
print('List of tuples
is:',lst)
lst.sort(key=reg_no)

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 6/
11/30/2020 DhruvKikan.ipynb - Colaboratory
# Part a) finished

List of tuples is: [('Rajat', 'Sen', '12345', '1', 'CSEE'), ('Jagat',


'Narain', '1341

# Part b) 1) start
infolist=['First Name','Last Name',' Reg. Year’ , ' Dept.']
no.',' op=open('tuplewriter.txt','r')
rd=op.read()
def
reg_no(element):
return element[2]
for k in
range(len(infolist)):
print(infolist[k],end=' ')
lst.sort(key=reg_no)
for k in range(len(infolist)
+1): p=lst[k]
print()
for x in range(len(p)):
print(p[x],end='\t\t')
# Part b) 1) finished

First Name Last Name Reg. no. Year Dept.


Sumder Kumra 11234 3 MME
Anu Sharma 11756 2 Biology
Rajat Sen 12345 1 CSEE
Jagat Narain 13467 3 CSEE
Kanti Bhushan 23211 3 CSEE
Sumita Trikha 23451 4 Biology

# Part b) 2) start
op=open('tuplewriter.txt','r')
rd=op.read()
infolist=['First Name','Last Name','Year']
def yearsort(element):
return element[3]
for k in range(len(infolist)):
print(infolist[k],end='\t')
lst.sort(key=yearsort),print()
'[]
for x in lst:
for k in range(len(infolist)+1):
p=x[k]
if ord(x[3])‹51:
if k!=2:
w.append(x[k])
for a in
range(len(w)):
if a‹=2:
print(w[a],end='\t\t
')
print()
for a in

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 7/
11/30/2020 DhruvKikan.ipynb - Colaboratory
range(len(w)): if
a>=3:
print(w[a],end='\t\t
') # Part b) 2) finished

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 8/
11/30/2020 DhruvKikan.ipynb - Colaboratory

First
Last Year
Name
Name 1
Rajat
Sen 2
Anu
Sharma

# Part b) 3) start
op=open('tuplewriter.txt','r')
lst,a,deptdict=[],[],{}
rd=op . read( )
deptlst=['MME','CSEE','Biology']
for i in rd:
a=rd.split()
try:
for x in
range(len(a)):
lst.append(a[4+5*x])
except IndexError:
pass
for x in lst:
deptdict[x]=0
for x in lst:
deptdict[x]+=1
for x in deptlst:
print(“The number of people in “+x+” department are:
“,deptdict[x]) # Part b) 3) finished

The number of people in MME department are:


1
The number of people in CSEE department
are: 3
The number of people in Biology department are: 2

4)
Write is a program that reads a file“myfile.txt” and builds a histogram (a
dictionary as {word:occurrence}) of the words in the file.
a) Now use histogram to print
i) Total number of words
ii) Number of different words
iii) The most common words
b) Using above text file “myfile.txt”, write a program that maps a list of
words read from the file to an integer representing the length of the
corresponding words.( use dictionary having key value pair as length : list
of word )
Now using above dictionary design a function find_longest_word() to display a list
of longest words from file.
Define a function filter_long_words(n) that takes an integer n and returns the
list of words that are longer than n from file.

op=open('myfile.txt','w')
op.writelines(”Neither apple or pine are in pineapple. Boxing rings are square.\nWriters
w op.close()
dict={}
op=open('myfile.txt','r')

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 9/
11/30/2020 DhruvKikan.ipynb - Colaboratory
rd=op.read()
# Part a) start
lst=rd.split()
for word in
lst:
dict[word]=0

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 1
11/30/2020 DhruvKikan.ipynb - Colaboratory
tor woro in
isr:
dict[word]+=1
no=0
wordlst=[]
for k in
dict:
no+=dict[k]
lower=0
for k in dict:
if
dict[k]>lower:
lower=dict[k]
x=k
print('Number of words is: ',no)
print('Number of different words is
:',dict)
print('The most common word is: "'+x+'" and it
occurs',lower,'times.') # Part a) finished

Number of words is:38


Number of different words is : {'Neither': 1, 'apple': 1, 'or': 1, 'pine': 1,
'are': The most common word is: "are" and it occurs 3 times.

# Part b) start
# create a dictionary having key as length of word and value as a list conting the
word op=open('myfile.txt','r')
rd=op.read()
wordlst=rd.split()
d={}
for word in
wordlst:
d[len(word)]=[]
for word ln wordlst:
d[len(word)].append(word)
def find_longest_word(dict):
lowest=0
for a in
dict: if
a>lowest:
lowest=a
print('List of longest words in file is:',dict[lowest])
find_longest_word(d)
def filter_longer_words(num,dict):
for a in dict:
if a>num:
print('Words with length longer than',num,'is: ',dict[a],'and their length is
:',a) n=int(input('Enter a number: '))
filter_longer_words(n,d)
# Part b) finished

List of longest words in file is: ['pineapple. ',


'opposites. '] Enter a number: 7
Words with length longer than 7 is: ['pineapple.', 'opposites. '] and their
length i! Words with length longer than 7 is: ['Overlook'] and their
https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 1
11/30/2020 DhruvKikan.ipynb - Colaboratory
length is : 8

5)
A /41r†1nnarv Cir stnmer mm ain s thr -Fnl lnw1ne kevs T rnnmnn . nnme . t4iz rat1nn T

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 1
11/30/2020 DhruvKikan.ipynb - Colaboratory

A binary file “hotel.dat” contains details of customer checked in the hotel.


Write a code in python to perform the following using pickle
module i)Read n dictionary objects and load them into the file
ii)Read all the dictionary objects from the file and print
them iii)Counts the number of customers present in the hotel.
iv)Display those customers from the file, who have stayed more than 2 days in the
hotel.

infolst=[{'Name':'John','RoomNo':56,'Duration' :1.5},{'Name' :'Jack','RoomNo':42,'Duration'


: import pickle
op=open('Hotel.dat','wb')
pickle.dump(infolst,op)
op.close()
op=open('Hotel.dat','rb')
lo=pickle.load(op)
num=int(input('Please enter a number:
')) # Part i) start
try:
if num<=len(lo):
for a in
range(num):
print(lo[a])
else:
print('Please enter a lower
number') except IndexError:
pass
# Part i) finished

Please enter a number: 2


{'Name': 'John', 'RoomNo': 56, 'Duration' : 1.5}
{'Name': 'Jack', 'RoomNo': 42, 'Duration' : 5}

# Part ii)
start for a in
lo:
pr1nt(a)
# Part ii) finished

{'Name': 'John', 'RoomNo': 56, 'Duration' : 1.5}


{'Name': 'Jack', 'RoomNo': 42, 'Duration' : 5}
{'Name': 'Jill', 'RoomNo': 551, 'Duration' : 9831}

# Part iii) start


for a in
range(len(lo)):
continue
print('There are',a+1,'people in the
hotel') # Part iii) finished

There are 3 people in the hotel

# Part iv)
start for k in
lo:
https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 1
11/30/2020 DhruvKikan.ipynb - Colaboratory
if k['Duration']>2:
print('The customer staying for more than 2 days
is',k) # Part iv) finished

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 1
11/30/2020 DhruvKikan.ipynb - Colaboratory

The customer staying for more than 2 days is {'Name': 'Jack', 'RoomNo': 42,
'Duration The customer staying for more than 2 days is {'Name': 'Jill',

'RoomNo': 551, 'Durati‹

6)
Sun Microsystems when held recruitment test, the file placement.csv containing the
below f The marks are from 5 different tests conducted and each column is out of 5
marks.
John - 4 - 3 - 4 - 2 - 5
Peter - 3 - 4 - 4 - 3 - 5...
a) Read the above file and print the data
b) Write User Defined Function to find total no of people who came for the
placement test
c) Write the UDF to find the top n Names on basis of total Marks

import csv
''func_name=str(input('Enter the name of the function:
')) def func_name():'''
rows=['S.no. ','Name','Test 1','Test 2','Test 3','Test 4','Test 5']
columns=[[1,'John',5,5,5,5,5],[2,'Peter',3,3,3,3,3],[3,'Gary',5,4,5,3,4],[4,'Dave',4,4,4,4
with open('placement.csv','w',newline=' ') as
a_file: writer=csv.writer(a_file)
writer.writerow(rows)
writer.writerows(columns)
# Part a) start
with open('placement.csv','r') as
a_file: read=csv.reader(a_file)
lines=list(read)
for x in lines:
for y in x:
print(y,end='\t')
print()
# Part a) finished

S.no. Name Test 1 Test 2 Test 3 Test 4 Test 5


1 John 5 5 5 5 5
2 Peter 3 3 3 3 3
3 Gary 5 4 5 3 4
4 Dave 4 4 4 4 4

# Part b)
start def
b_part():
with open ('placement.csv') as
r_file: read=csv.reader(r_file)
lines=list(read)
for x in
range(1en(lines)):
continue
print(x)
b_part()
# Part b)

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 1
11/30/2020 DhruvKikan.ipynb - Colaboratory
finished 4

# Part c) start
n=int(input('Enter the amount of top contestants required: '))

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 1
11/30/2020 DhruvKikan.ipynb - Colaboratory

topnames=[]
marks,d1,d2=[],{},{}
def c_part(n):
with open('placement.csv') as r_file:
read=csv.reader(r_file)
lines=list(read)
for x in lines[1:]:
topnames.append(x)
for k in lines[1:]: marks.append(int(k[2])+int(k[3])+int(k[4])
+int(k[5]))
for y in range
(len(marks)):
d1[y+1]=marks[y]
marks.sort(reverse=True)
for y in range(len(marks)):
d2[y+1]=marks[y]
index=1
while index<=n:
print(d2[index])
index+=1
c_part(n)
# Part c) finished

Enter the amount of top contestants


required: 3 20
17
16

7)
Write a program to input a number and then call the functions
a) count(n) which returns the number of digits
b) reverse(n) which returns the reverse of a number
c) hasdigit(n) which returns True if the number has a digit else False
d) show(n) to show the number as sum of place values of the digits of the number

# Part a) start
n=input(“Enter a Number:
") def count(n):
print('Digits in “n" are: ',len(n))
count(n)
# Part a) finished

Enter a Number: 2132156


D1g1ts 1n "n" are: 7

# Part b) start
n=input(“Enter a Number:
") def reverse(n):
print('“n" reversed is: ',n[-1::-
1]) reverse(n)
# Part b) finished

Enter a Number:

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 1
11/30/2020 DhruvKikan.ipynb - Colaboratory
684615 "n" reversed
is: 516486

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 1
11/30/2020 DhruvKikan.ipynb - Colaboratory

# Part c) start
n=input(“Enter a Number:
“) def hasdigit(n):
for x in n:
falg=False

int(x)
falg=True
break
except:
passas
print('“n“ has digits:
',falg) hasdigit(n)
# Part c) finished

Enter a Number:
evd54 “n” has
digits: True

# Part d) start
n=input(“Enter a Number:
“) def show(n):
print('Place Value=
',end='') lst=[]
for x in n:
lst.append(x)
print(n,end=”=”)
for x in range(len(lst)):
print(int(lst[x])*10**(len(1st)-x-1),end=““)
if x!=len(lst)-1:
print(end=”+”)
show(n)
# Part d) finished

Enter a Number: 65684


Place Value= 65684=60000+5000+600+80+4

8)
A Number is a perfect number if the sum of all the factors of the
number (including 1) excluding itself is equal to number.
Write functions
a) GenerateFactors() to populate a list of factors
b) isPrimeNum() to check whether the number is prime number or not
c) isPerfectNum() to check whether the number is perfect number or not

# Part a) start
num=int(input(”Enter a Number:
“)) def GenerateFactors(num):
global lst
lst=[]
for x in range(1,num):
if num%x==0:

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 1
11/30/2020 DhruvKikan.ipynb - Colaboratory
lst.append(x)

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 2
11/30/2020 DhruvKikan.ipynb - Colaboratory

print('Factors:',lst)
GenerateFactors(num)
# Part a finished

Enter a Number: 654


Factors: [1, 2, 3, 6, 109, 218, 327]

# Part b) start
num=int(input(”Enter a Number:
“)) def isPrimeNo(num):
global lst
if len(lst)==1:
print(”It IS A prime
number“) else:
print(”It IS NOT A prime
number") isPrimeNo(num)
# Part b) finished

Enter a Number: 654


It IS NOT A prime number

# Part c) start
num=int(input(”Enter a Number:
”)) def isPerfectNo(num):
global lst
sum=0
for x in
lst:
sum+=x
if sum==num:
print(”It IS A perfect
number“) else:
print(”It IS NOT A perfect
number“) isPerfectNo(n)
# Part c) finished

Enter a Number: 654


It IS NOT A perfect number

9)
Pascal’s triangle is a number triangle with numbers arranged in staggered rows such
that a This equation is the equation for a binomial coefficient. Write a recursive
function in Py

import
math def
tri(i):
n = int(input(”Enter Number:
”)) for x in range(n):
i-"
for y in range(x+1):
i+=str(math.factorial(x)//(math.factorial(y)*math.factorial(x-y)))
print(i)
https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 2
11/30/2020 DhruvKikan.ipynb - Colaboratory

Enter Number: 6
1
11
121
1331
14641
15101051

10)
Input number in decimal and desired type
(Specify B for Binary, 0 for Octal, H for Hexadecimal) for output.

# Part a) start
def
bin(lst,num):
rem=num%2
lst.append(rem)
num=num//2
if num != 0:
bin(lst,num)
else:
lst.reverse()
for x in
lst:
print (x,end=””)
lst=[]
num=int(input(”Enter decimal number:
“)) bin(lst,num)
# Part a) finished

Enter decimal number:


654 1010001110

# Part b)
start lst=[]
num=int(input(”Enter decimal number:
“)) def oct(lst,num):
rem=num%8
lst.append(rem)
num=num//8
if num!=0:
oct(lst,num)
else:
1st.reverse()
for x in
lst:
print (x,end=””)
oct(lst,num)
# Part b) finished

Enter decimal number:


654 1216

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 2
11/30/2020 DhruvKikan.ipynb - Colaboratory

# Part c) start
num=int(input(”Enter decimal number: “))

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 2
11/30/2020 DhruvKikan.ipynb - Colaboratory
oet nex¿num :
st _....
while num!=0:
if num%16>=10:
st+=chr(55+(num%16))
else:
st+=str(num%16)
num//=16
print(st[::-1])
Hex(num)
# Pact c) finished

Enter decimal number:


654 28E

11)
Write a program to input a list and write the function for the following:
a) To sort list using bubble sort and find efficiency
b) To search an element using linear search and find efficiency
c) To search an element using binary search and find efficiency

# Part a) start
l=[]
n=int(input('Enter the length of required list:
')) for x in range(n):
k=int(input('Enter element: '))
1.append(k)
def
bubble(1)
: flag=0
while
flag==0:
flag=1
for x in range(len(1)-
1): if 1[x+1]<l[x]:
flag 0
e=l[x]
l[x]=l[x+1]
l[x+l]=e

bubble(1)
print(1)
# Part a) finished

Enter the length of required


list: 6 Enter element: 5
Enter element: 8
Enter element: 2
Enter element: 1
Enter element: 3
Enter element: 6
[1, 2, 3, 5, 6, 8]

# Part b) start

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 2
11/30/2020 DhruvKikan.ipynb - Colaboratory
l=[]
n=int(input('Enter the length of required list: '))

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 2
11/30/2020 DhruvKikan.ipynb - Colaboratory
for x in range(n):
k=int(input('Enter element: '))
1.append(k)
fin=int(input('Enter the number to be found:
')) print()
def
linear(l,fin):
count=0
for y in
range(len(l)):
count+=1
if 1[y]==fin:
print('The number',fin,'is at',y)
print('The number of steps required=
',count) break
linear(l,fin)
# Part b) finished

Enter the length of required


list: 9 Enter element: 1
Enter element: 2
Enter element: 3
Enter element: 4
Enter element: 5
Enter element: 6
Enter element: 7
Enter element: 8
Enter element: 9
Enter the number to be found: 9

The number 9 is at 8
The number of steps required= 9

# Part c) start
l=[]
n=int(input('Enter the length of required list:
')) for x in range(n):
k=int(input('Enter element: '))
1.append(k)
def bin(l,m,start,end):
global count
count=0
if end>=start:
count+=1
mid=(start+end)//2
if 1[mid]==m:
count+=1
return
mid
elif
1[mid]>m:
count+=1
return bin(l,m,start,mid-1)
elif 1[mid]<m:
count+=1
return bin(l,m,mid+1,end)

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 2
11/30/2020 DhruvKikan.ipynb - Colaboratory
else:
count+=1
return -1

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 2
11/30/2020 DhruvKikan.ipynb - Colaboratory

b=int(input('Enter number to be found:


')) pos=bin(l,b,0,len(1)-1)
print()
print('The number is at: ',pos)
print('The number of steps required=
',count) # Part c) finished

Enter the length of required


list: 9 Enter element: 1
Enter element: 2
Enter element: 3
Enter element: 4
Enter element: 5
Enter element: 6
Enter element: 7
Enter element: 8
Enter element: 9
Enter number to be found: 9

The number is at: 8


The number of steps required= 2

12)
Create a graphical application for Simple Interest Calculator that accepts user
inputs for Calculate simple interest write the output using a message box on the
screen. Use the tkin

import tkinter as tk
root=tk. Tk( )

mainlabel=tk.Label(root,text=“Simple Interest Calculator",font=(”bold",20))


mainlabel.grid(row=0)

principal=tk.Label(root,text=“Enter principal amount: “)


principal.grid(column=0,row=1)

principalentry=tk.Entry(root)
principalentry.grid(column=1,row=l)

ratelabel=tk.Label(root,text=“Enter rate of interest: “)


ratelabel.grid(column=0,row=2)

rateentry=tk.Entry(root)
rateentry.grid(column=1,row=2)

timelabel=tk.Label(root,text=“Enter duration for loan: “)


timelabel.grid(column=0, row=3)

timeentry=tk.Entry(root)
timeentry.grid(column=1, row=3)

resultlabel=tk.Label(root)
resultlabel.grid(column=0, row=4)

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 2
11/30/2020 DhruvKikan.ipynb - Colaboratory
def click():

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 2
11/30/2020 DhruvKikan.ipynb - Colaboratory

resultlabel.config(text =“Amount is: “+(str(int(principalentry.get())+((int(principale


enterbutton=tk.Button(root,text=”Enter“,command=click)
enterbutton.grid(column=0, row=5)
root.mainloop()

13)
Create a stack to take in a stack of numbers and then simulate a ring game.
A ring stand is such that only a ring of higher diameter can be placed on lower
one.
The diameters are given by the user and the program will compare the diameter of
ring at s with the diameter of ring to be placed if condition specified is true
ring is added to the stack otherwise keep popping and put them into temporary ring
stand to arrange them into a

n=int(input(“Enter length of stack: “))


l=[]
tmp=[]
for x in range(n):
diam=int(input(”Enter diameter:
“)) if x==0:
1. append(diam)
else:
if diam>l[len(1)-1]:
1.append(diam)
elif diam‹l[len(1)-1]:
pop=l.pop(len(1)-1)
tmp.append(pop)
1.append(diam)
print(”The final stack is: “,1)
print(”The temporary stack is: “,tmp)

Enter length of stack:


5 Enter diameter: 6
Enter diameter: 2
Enter diameter: 3
Enter diameter: 4
Enter diameter: 7
The final stack is:[2, 3, 4,
7] The temporary stack is:
[6]

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 3
11/30/2020 DhruvKikan.ipynb - Colaboratory

14J

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 3
11/30/2020 DhruvKikan.ipynb - Colaboratory

Create a program to take in a list reg_no, Name, admission_to_class (Nursery, KG,


I) and a
a) Add data to the queue.
b) Display length of the queue.
c) Print a report showing number of applications received for admission to each
class

l=[]
def add(1):
x=input(“ENTER: reg_no, Name,admission_to_class... (seperate by comma) “)
1.append(x.split(','))
def
leng(1):
k=len(1)
print(“The number of admissions are: “,k,”data given below”)
for x in l:
print(x)
def num_adm(1):
Nurs=0
Kg=0
Ist=0
for x in l:
if x[2]==“Nursery“:
Nurs+=1
elif x[2]==“KG”:
Kg+=1
elif x[2]==“Ist”:
Ist+=1
print(“number of applications received for
nursery“,Nurs) print(“number of applications received
for KG”,Kg) print(“number of applications received
for 1st”,Ist) print()

while
True:
print()
ans=input(“Type:\nAdd to add \nView to view data \nReport to see report \nQuit to
quit\n print()
if ans==“Add“:
add(1)
elif ans==“View“:
leng(1)
elif
ans==“Report”:
num_adm(1)
elif ans==“Quit“:
break

Type:
Add to add
View to view data
Report to see
report Quit to
quit
Add

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 3
11/30/2020 DhruvKikan.ipynb - Colaboratory

ENTER: reg_no, Name,admission_to_class... (seperate by comma) 1,Tony,Nursery

Type:
Add to add
View to view data

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 3
11/30/2020 DhruvKikan.ipynb - Colaboratory

Report to see
report Quit to
quit
Add

ENTER: reg_no, Name,admission_to_class... (seperate by comma) 2,Fony,KG

Type:
Add to add
View to view data
Report to see
report Quit to
quit
Add

ENTER: reg_no, Name,admission_to_class... (seperate by comma)

3,Pony,Ist Type:
Add to add
View to view data
Report to see
report Quit to
quit
View

The number of admissions are: 3 data given


below ['1', 'Tony', 'Nursery']
['2', 'Fony', 'KG']
['3', 'Pony', 'Ist']

Type:
Add to add
View to view data
Report to see
report Quit to
quit
Report

number of applications received for


nursery 1 number of applications received
for KG 1 number of applications received
for 1st 1

Type:
Add to add
View to view data
Report to see
report Quit to
quit
Add

Database management question 1 part i) t

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 3
11/30/2020 DhruvKikan.ipynb - Colaboratory
mysql> se1ect*from watches;

WatchID | Watch Name | Price | Type | Stored Qty

WB01
High Time | 1B000 Unisex 1B0
W002
Life Time | 15000 Ladies 150
WB03
Wave | 20000 Gents 200
W004
High Fashion | 7000 Unisex 250
WB05
Golden Time | 2500 Gents 1B0

3 rows in set (0.0B

ser) mysql> se1ect*from

sale;

WatchID | Qty Sold | Quarter

NB81 IB
W003
WB02 2B
W003 18
NB81 15
W002 28
WBOS 1B
W003 15

8 rows in set (0.00 ser)

mysq1> select w.Watch Name, s.Qty Sold from matches w,sale s where Quarter=1 and

w.WatchID=s.WatchID; Watch_Name | Qty_Sold

High Time l0
Wave

2 rows in set (B. 81 sec)

Database management question 1 part ii) t

mysql> select w.WatchID, w.Watch Name, w.Price, w.Type, w.5tored Qty, s.Qty_Sold, s.Quarter from watches
w, sal e s where w.WatchID=s.WatchID and Watch_Name like '%Time’;

WatchID | Watch_Name | Price | Type| Stored Qty | Qty_Sold | Quarter

Iu 1
W001 | High Time | 10000 | Unisex 1B0
W001 | High Time | 10000 | Unisex 100 15 s
WOOZ | Life Time | 15000 | Ladies 1sa Z0 z
WOOZ | Life Time | 15000 | Ladies 1sa s
W00â | Golden Time | 2300 | Gents 1B0 Iu
s
5 rDws In set 8. 81 sec)

mysql>

Database management question 1 part iii) t

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 3
11/30/2020 DhruvKikan.ipynb - Colaboratory

Databse management question 1 part iv) t

Database management question 1 part v) t

Database management question 2 t

import mysql.connector
mydatabase=mysql.connector.connect(host='localhost',user='root',passwd='pass',database='cb
mycursor=mydatabase.cursor()
def insert(itemcod,itemnam,price):
ins=('Insert into item values(itemcode,itemname,price) values(%s,%s,%s)')
l=[]
1. append(itemcod)
1.append(itemnam)
1.append(price)
»l=t»nlorl;
https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 3
11/30/2020 DhruvKikan.ipynb - Colaboratory

mycursor.execute(ins,val)
mydatabase.commit

def disp():
mycursor.execute('select*from item')
for x in mycursor:
print(x)

def search(searchitem):
mycursor.execute('select*from item')
for x in mycursor:
if searchitem==str(x):
print('Record
found!')
else:
print('Record not found :(')

while True:
print('Type Display to view the items; Search to search for a record; Insert to
enter k=str(input('Enter process: '))
if k=='Search' :
searchitem=str(input('Enter item to be searched: '))
search(searchitem)
elif k=='Display':
disp()
elif k=='Insert' :
itemcod=str(insert('Enter item code: '))
itemnam=str(insert('Enter item name: '))
price=float(input('Enter the price: '))
insert(itemcod,itemnam,price)
elif k=='Quit'
: break
else:
break

https://coIab.research.googIe.com/drive/1ki0mujECq8u2q4y4Lh38319h_WUCzoUZ? 3

You might also like