You are on page 1of 57

AN

ASSIGNMENT FILE

Guided By: Submitted By:

XII - C
INDEX
SR TITLE PAGE
NO . NO.
1. Program to calculate simple interest 4

2. Program that receives two numbers in a function and returns the results 5
of all arithmetic operations( +,-,*,/,%) on these numbers

3. Program to input a number and test if it is a prime number . 6

4. Write a program to check whether the given number is palindrome or 7


not.

5. Write a program to check whether the given number is Armstrong 8


number or not .

6. Write a program to print the following pattern 9

7. Write a program to take two strings from user and displays the smaller 10
string in single line and larger string

8. Program to find frequencies of all elements of a list . Also , print the list 11-12
of unique elements in the list and duplicate elements in the given list

9. Write a program to find the second largest number of the list of 13


numbers

10. Write a program to check if the elements in the first half of a tuple are 14
sorted in ascending order or not

11. Program to count the frequency of a list of elements using a dictionary 15

Write a program to create a dictionary with the roll number, name and
12. marks of n students in a class and display the names of students who 16-17
have marks above 75
13. Write a program to input your friend’s names and their phone numbers 18-22
and store them in the dictionary as the key-value pair

14. Program to sort a sequence using insertion sort. 23

15. Program to sort a list using bubble sort. 24

16. Write a program that inputs main string and then creates an encrypted 25
string by embedding a short symbol based string after each character

17. Write a random number generator that generates random numbers 26


between 1 and 6(simulates a dice).

18. Write a program to read a text file line by line and display each word 27
separated by a ‘#’

19. Write a program to read a text file and display the count of vowels and 28
consonants in the file

20. Write a program to get student data(roll no. , name and marks) from 29
user and write onto a binary file

21. Write a program to append student records to file created in previous 30


program, by getting data from user

22. Write a program to open file Stu.dat and search for records with roll 31
numbers as 46 or 48 . If found display the records

23. Write a program to update the records of the file Stu.dat so that those 32
who have scored more than 81.0, get additional bonus marks of 2

24. Write a program to create a CSV file to store student data(Rollno. , 33


Name , Marks). Obtain data from user and write 5 records into the file.
Write a program to read following details of sport’s performance
25. (sport , competitions, prizes-won) of your school and store into a csv file 34
delimited with tab character

26. Inserting an element in a sorted array using traditional algorithm 35-36

27. Deletion of an element from a sorted linear list. 37-38

28. Python program to implement stack operations. 39-41


29. Program to implement Queue operations 42-46

30. Write SQL commands for following realtion STUDENT 47-50

31. Write SQL queries for following database LIBRARY 50-54

32. Write a python program that displays a first three rows fetched from 55
student table of MySQL database “test”.

33. Write a python database connectivity script that deletes records from 56
category table of database items that have name = ‘Stockable’
Q.1 Program to calculate simple interest using a function interes() that can receive
principal amount , time and rate and returns calculated simple interest. Do specify
default values for rate and time as 10% and 2 years respectively .

def interest(principal, time = 2 , rate = 0.10):


return principal*rate*time
#__main__
Prin = float(input(“Enter principal amount:”))
print(“Simple interest with default ROI and time value is:”)
Si1 = interest(Prin)
Roi = float(input(“Enter rate of interest (ROI):”))
Time = int(input(“Enter time in years:”))
print (“Simple interest with your provided ROI and time value is:”)
Si2 = interest( Prin, time, Roi/100)
print(“Rs.” , Si2)
Q.2 Program that receives two numbers in a function and returns the results of all
arithmetic operations( +,-,*,/,%) on these numbers

def arCalc( x , y ) :
return x+y , x-y , x*y , x/y , x%y
#__main__
num1 = int(input( “ enter number 1 :” ))
num2 = int(input( “ enter number 2:” ))
add , sub , mult , div , mod = arCalc(num1,num2)
print( “sum of given numbers:” , add )
print( “subtraction of given numbers:” , sub )
print( “product of given numbers:” , mult )
print( “division of given numbers:” , div )
print( “modulo of given numbers:” , mod )
Q.3 Program to input a number and test if it is a prime number .

num = int(input("ENTER NUMBER:"))


lim = int(num/2) + 1
for i in range(2,lim):
rem = num % i
if rem == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
Q.4 Write a program to check whether the given number is palindrome or not.

num = int(input("ENTER NUMBER:"))


wnum = num
rev = 0
while( wnum > 0):
dig = wnum % 10
rev = rev*10 + dig
wnum = wnum // 10
if(num == rev):
print("Number", num, "is a palindrome")
else:
print("Number", num , "is not a palindrome")
Q.5 Write a program to check whether the given number is Armstrong number or not .
(Note: If a 3 digit number is equal to the sum of the cubes of its each digit , then it is an
Armstrong number )

num = int(input(" Enter a 3 digit number: "))


sum = 0
temp = num
while(temp > 0 ):
digit = temp % 10
sum += digit **3
temp //= 10
if (num==sum):
print(num , "is an Armstrong number")
else:
print(num , "is not an Armstrong number")
Q.6 Write a program to print the following pattern :

n=5 #for number of lines


# upper half
k = round(n/2) * 2 #for initial spaces
for i in range(0,n,2):
for j in range(0,k+1):
print(end=" ")
for j in range(0,i+1):
print("*", end=" ")
k = k -2
print()
#lower half
k=1
for i in range(n-1,0,-2):
for j in range(0,k+2):
print(end = " ")
for j in range(0,i-1):
print("*", end=" ")
k=k+2
print()
Q.7 Write a program to take two strings from user and displays the smaller string in
single line and larger string as per this format :

FOR EXAMPLE:

a = input( "Enter first string:" )


b = input("Enter second string:" )
a, b = min(a, b), max(a, b)
print(a)
t = len(b)
for i in range(t//2):
print(i*" "+b[i]+(t-2*(i+1))*" "+b[-(i+1)])
if t%2 == 1:
print((t//2)*" "+b[t//2])
Q.8 Program to find frequencies of all elements of a list . Also , print the list of unique
elements in the list and duplicate elements in the given list.

lst = eval(input("Enter list:"))


length = len(lst)
uniq = []
dupl = []
count = i = 0
while i < length :
element = lst[i]
count = 1
if element not in uniq and element not in dupl:
i += 1
for j in range(i, length):
if element == lst[j]:
count += 1
else:
print("Element", element,"frequency:", count)
if count ==1:
uniq.append(element)
else:
dupl.append(element)
else:
i += 1
print("Orignial list", lst)
print("Unique elements list",uniq)
print("Duplicates elements list", dupl)
Q. 9 Write a program to find the second largest number of the list of numbers.

lst = eval(input("Enter list:"))


length = len(lst)
biggest = secondbiggest = lst[0]
for i in range(1, length):
if lst[i] > biggest :
secondbiggest = biggest
biggest = lst[i]
elif lst[i] > secondbiggest:
secondbiggest = lst[i]
print("Largest number of the list:", biggest)
print("Second largest number of the list:", secondbiggest)
Q.10 Write a program to check if the elements in the first half of a tuple are sorted in
ascending order or not.

tup = eval(input("Enter a tuple:"))


ln = len(tup)
mid = ln//2
if ln % 2 == 1:
mid = mid + 1
half = tup[:mid]
if sorted(half) == list(tup[:mid]):
print("First half is sorted")
else:
print("First half is not sorted")
Q.11 Program to count the frequency of a list of elements using a dictionary.

import json
sentence = "This is a super idea This\
idea will change the idea of learning"
words = sentence.split()
d = {}
for one in words:
key = one
if key not in d:
count= words.count(key)
d[key] = count
print("Counting frequencies in list \n",words)
print(json.dumps(d, indent=1))
Q.12 Write a program to create a dictionary with the roll number, name and marks of n
students in a class and display the names of students who have marks above 75.

n = int(input("How many Students?"))


stu = {}
for i in range(1,n+1):
print("Enter details of student", (i))
rollno = int(input("Roll number:"))
name = input("Name:")
marks = float(input("Marks:"))
d = {"Roll_no" : rollno, "Name" : name,\
"Marks" : marks}
key = "Stu" + str(i)
stu[key] = d
print("Students with marks > 75 are:")
for i in range(1,n+1):
key = "Stu" + str(i)
if stu[key]["Marks"] >= 75:
print(stu[key])
Q.13 Write a program to input your friend’s names and their phone numbers and store
them in the dictionary as the key-value pair . Perform the following operations on the
dictionary :
(a) Display the name and phone number of all your friends
(b) Add a new key-value pair in this dictionary and display the modified dictionary
(c) Delete a particular friend from dictionary
(d) Modify the phone number of an existing friend
(e) Check if a friend is present in the dictionary or not
(f) Display the dictionary in sorted order of names

n = int(input("How many friends?"))


fd = {}
for i in range(n):
print("Enter details of friend",(i+1))
name = input("Name:")
ph = int(input("Phone:"))
fd[name] = ph
print("Friends dictionary is",fd)
ch = 0
while ch != 7:
print("\tMenu")
print("1. Display all friends")
print("2. Add new friend")
print("3. Delete a friend")
print("4. Modify a phone number")
print("5. Search for a friend")
print("6. Sort on names")
print("7. Exit")
ch = int(input("Enter your choice (1..7):"))
if ch ==1:
print(fd)
elif ch ==2:
print("Enter details of new friend")
name = input("Name:")
ph = int(input("Phone:"))
fd[name] = ph
elif ch ==3:
nm = input("Friend Name to be deleted:")
res = fd.pop(nm,-1)
if res != -1:
print(res,"deleted")
else:
print("No such friend")
elif ch ==4:
name = input("Friends Name:")
ph = int(input("changed phone:"))
fd[name] = ph
elif ch ==5:
name = input("Friends Name:")
if name in fd:
print(name,"exists in the dictionary")
else:
print(name,"does not exist in dictionary")
elif ch ==6:
lst = sorted(fd)
print("{",end = " ")
for a in lst:
print(a,":",fd[a],end = " ")
print("}")
elif ch ==7:
break
else:
print("Valid choices are 1..")
Q.14 Program to sort a sequence using insertion sort.

aList = [15,6,13,22,3,52,2]
print("Original list is:",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)
Q.15 Program to sort a list using bubble sort.

alist = [15,6,13,22,3,52,2]
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)
Q.16 Write a program that inputs main string and then creates an encrypted string by
embedding a short symbol based string after each character . The program should also
be able to produce the decrypted string from encrypted string.

def encrypt(sttr,enkey):
return enkey.join(sttr)
def decrypt(sttr,enkey):
return sttr.split(enkey)
#-main-
mainstring = input("enter main string:")
encryptstr = input("enter encryption key:")
enstr = encrypt(mainstring,encryptstr)
delst = decrypt(enstr,encryptstr)
destr = "".join(delst)
print("the encrypted string is",enstr)
print("string after dcryption is:",destr)
Q.17 Write a random number generator that generates random numbers between 1 and
6(simulates a dice).

import random
min = 1
max = 6
rollagain = "y"
while rollagain == "y" or rollagain =="Y":
print("Rolling the dice...")
val = random.randint(min,max)
print("You get...:",val)
rollagain = input("Roll the dice again? (y/n)..")
Q.18 Write a program to read a text file line by line and display each word separated by
a ‘#’.

myfile = open("answer.txt" , "r")


line = " "
while line:
line = myfile.readline()
for word in line.split():
print(word,end = '#')
print()
myfile.close()
Q.19 Write a program to read a text file and display the count of vowels and consonants
in the file.

myfile = open("answer.txt","r")
ch = ""
vcount = 0
ccount = 0
while ch:
ch = myfile.read(1)
if ch in['a','A','e','E','i','I','o','O','u','U']:
vcount = vcount +1
else:
ccount = ccount +1
print("vowels in the file:",vcount)
print("consonants in the file:",ccount)
myfile.close()
Q.20 Write a program to get student data(roll no. , name and marks) from user and
write onto a binary file. The program should be able to get data from the user and write
onto the file as long as the user wants

import pickle
stu= {}
stufile = open('Stu.dat', 'wb')
ans = 'y'
while ans == 'y' :
rno = int(input("Enter roll number : "))
name = input("Enter name :")
marks = float(input("Enter marks : "))
stu['Rollno'] = rno
stu['Name'] = name
stu['Marks'] = marks
pickle.dump(stu, stufile)
ans = input("Want to enter more records? (y/n)...")
stufile.close()
Q.21 Write a program to append student records to file created in previous program, by
getting data from user.

import pickle
stu = { }
stufile = open('Stu.dat', 'ab')
ans = 'y'
while ans == 'y' :
rno = int(input("Enter roll number :"))
name = input("Enter name :")
marks = float( input("Enter marks: "))
stu['Rollno'] = rno
stu[ 'Name'] = name
stu[ 'Marks'] = marks
pickle.dump(stu, stufile)
ans = input("Want to append more records? (y/n)...")
stufile.close()
Q.22 Write a program to open file Stu.dat and search for records with roll numbers as
46 or 48 . If found display the records.

import pickle
stu = {}
found = False
fin = open('Stu.dat', 'rb')
searchkeys = [46, 48]
try:
print("Searching in File Stu.dat ...")
while True :
stu = pickle.load(fin)
if stu['Rollno'] in searchkeys :
print(stu)
found = True
except EOFError:
if found == False :
print("No such records found in the file")
else:
print("Search successful.")
fin.close()
Q.23 Consider the binary file Stu.dat storing student details, which you created in
earlier programs. Write a program to update the records of the file Stu.dat so that those
who have scored more than 81.0, get additional bonus marks of 2.

import pickle
stu = {}
found = False
fin = open('Stu.dat', 'rb+')
try:
while True :
rpos = fin.tell()
stu = pickle.load(fin)
if stu['Marks'] > 81 :
stu['Marks'] += 2
fin.seek(rpos)
pickle.dump(stu, fin)
found = True
except EOFError:
if found == False:
print("Sorry, no matching record found.")
else:
print("Record(s) successfully updated.")
fin.close()
Q.24 Write a program to create a CSV file to store student data(Rollno. , Name ,
Marks). Obtain data from user and write 5 records into the file.

import csv
fh = open("Student.csv", "w")
stuwriter = csv.writer(fh)
stuwriter.writerow(['Rollno', 'Name', 'Marks'])
for i in range(5):
print("Student record", (i+1))
rollno = int(input("Enter rollno:"))
name = input("Enter name:")
marks = float(input("Enter marks:"))
sturec = [rollno, name, marks ]
stuwriter.writerow(sturec)
fh.close()
Q.25 Write a program to read following details of sport’s performance (sport ,
competitions, prizes-won) of your school and store into a csv file delimited with tab
character .

import csv
fh = open("Sport.csv", "w")
swriter = csv.writer(fh, delimiter='\t')
swriter.writerow( ['Sport', 'Competitions', 'Prizes won'])
ans = 'y'
i=1
while ans == 'y':
print("Record", i)
sport=input("Sport name:")
comp = int(input("No. of competitions participated :"))
prizes = int(input("Prizes won:"))
srec = [ sport, comp, prizes ] # create sequence of user data
swriter.writerow(srec)
i = 1+1
ans = input("Want to enter more records? (y/n)..")
fh.close()
Q.26 Inserting an element in a sorted array using traditional algorithm.

def FindPos (AR, item) :


size = len(AR)
if item < AR[0] :
return 0
else :
pos = -1
for i in range(size -1):
if (AR[i] <=item and item < AR[i+1] ):
pos = i +1
break
if (pos == -1 and i <= size -1):
pos = size
return pos
def Shift( AR, pos ):
AR.append(None)
size = len (AR)

i = size -1
while i >= pos :
AR[i] = AR[i-1]
i =i-1
#_main_
myList = [18, 29, 30, 40, 50, 60, 70]
print("The list in sorted order is")
print(myList)
ITEM = int(input("Enter new element to be inserted :"))
position = FindPos( myList, ITEM)
Shift (myList, position)
myList[position] = ITEM
print("The list after inserting", ITEM, "is")
print(myList)
Q.27 Deletion of an element from a sorted linear list.

def Bsearch(AR, ITEM) :


beg = 0
last = len(AR) - 1
while (beg <= last):
mid = (beg + last)//2
if ITEM == AR[mid] :
return mid
elif (ITEM > AR[mid]):
beg = mid + 1
else :
last = mid - 1
else :
return False
#_main_
myList = [10, 20, 30, 40, 50, 60, 70]
print("The list in sorted order is")
print(myList)
ITEM = int(input("Enter element to be deleted :"))
position = Bsearch(myList, ITEM)

if position :
del myList[position]
print("The list after deleting", ITEM, "is")
print(myList)
else:
print("SORRY! No such element in the list")
Q.28 Python program to implement stack operations.

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 Peek(stk):
if isEmpty(stk):
return "Underflow"
else:
top = len(stk) - 1
return stk[top]
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. Peek")
print("4. Display stack")
print("5. Exit")
ch = int(input("Enter your choice (1-5) :"))
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:
item = Peek (Stack)
if item == "Underflow" :
print("Underflow! Stack is empty!")
else:
print("Topmost item is", item)
elif ch == 4 :
Display (Stack)
elif ch == 5 :
break
else:
print("Invalid choice!")
Q.29 Program to implement Queue operations.

def cls():
print("\n"* 100)

def isEmpty (Qu):


if Qu == [] :
return True
else :
return False

def Enqueue (Qu, item):


Qu.append(item)
if len(Qu) == 1 :
front = rear = 0
else :
rear = len(Qu) - 1

def Dequeue (Qu):


if isEmpty(Qu):
return "Underflow"
else:
item = Qu.pop(0)
if len(Qu) == 0:
front= rear = None
return item

def Peek(Qu):
if isEmpty(Qu):
return "Underflow"
else:
front = 0
return Qu[front]

def Display(Qu):
if isEmpty(Qu):
print("Queue Empty!")
elif len(Qu) == 1:
print(Qu[0], "<== front, rear")
else:
front = 0
rear = len(Qu) - 1
print(Qu[front], "<- front")
for a in range(1, rear):
print(Qu[a])
print(Qu[rear], "<-rear")
#_main_program
queue = []
front = None
while True :
cls()
print("QUEUE OPERATIONS")
print("1. Enqueue")
print("2. Dequeue")
print("3. Peek")
print("4. Display queue")
print("5. Exit")
ch = int(input("Enter your choice (1-5): "))
if ch == 1:
item = int(input("Enter item :"))
Enqueue (queue, item)
input("Press Enter to continue...")
elif ch == 2:
item - Dequeue (queue)
if item == "Underflow":
print("Underflow! Queue is empty!")
else:
print("Dequeue-ed item is", item)
input("Press Enter to continue...")
elif ch == 3:
item = Peek (queue)
if item == "Underflow" :
print("Queue is empty!")
else :
print("Frontmost item is", item)
input("Press Enter to continue...")
elif ch == 4 :
Display(queue)
input("Press Enter to continue...")
elif ch == 5:
break
else:
print("Invalid choice!")
input("Press Enter to continue...")
Q.30 Given the following student relation :

Write SQL commands for (a) to (f) and write output for (g).

(a) To show all information about students of history department

(b) To list the names of female students of history department


(c) To list names of all students with their date of admission in ascending order.

(d) To display student’s Name, Fee, Age for male Students only.

(e) To count the number of student with Age < 23.


(f) To insert a new row in the STUDENT table with the following data :
9, “Zaheer”,36, “Computer” , {12/03/97}, 230 , “M”

(g) Give the output of following SQL statements:


1) Select COUNT(distinct department) from students;
2) Select MAX(age) from students where sex = 'F';
3) Select AVG(Fee) from students where Dateofadm < '01/01/98';
4) Select SUM(Fee) from students where Dateofadm <'01/01/98';
Q.31 Given the following tables for a database LIBRARY :

Write SQL queries for (a) to (f):


(a) To show Book name , Author name and Price of books of First Publ. publishers.

(b) To list the names from books of text type.


(c) To display the names and prices from books in ascending order of their price.

(d) To increase the price of all books of EPB Publishers by 50 .

(e) To display the Book_id,Book_Name and Quantity_Issued for all books which
have been issued.(The query will require contents from both the tables.)
(f) To insert a new row in the table Issued having the following data : "F0003",1

(g) Give the output of the following queries based on the above tables

1) Select COUNT(*) FROM Books;

2) Select MAX(Price) from books WHERE Quantity >= 15;

3) Select Book_Name , Author_Name from books WHERE Publishers = 'EPB' ;


4) Select COUNT(DISTINCT Publishers) from books WHERE Price >= 400 ;
Q.32 Write a python program that displays a first three rows fetched from student table
of MySQL database “test”.
(NOTE: user is “learner” and password is “fast”)

import mysql.connector as sqltor


mycon = sqltor.connect(host = "localhost", user = "learner", passwd = "fast", database =
"test")
if mycon. is_connected() == False:
print('Error connecting to MySQL database')
cursor = mycon.cursor()
cursor.execute("select * from student")
data = cursor.fetchmany(3)
count = cursor.rowcount
for row in data :
print(row)
mycon.close()
Q.33 Write a python database connectivity script that deletes records from category
table of database items that have name = ‘Stockable’

import mysql.connector as ctor


dbcon = ctor.connect(host = "localhost", user = "learner", passwd = "fast",
database = "items")
cursor = dbcon.cursor()
sql1 = "DELETE FROM category WHERE name= '%s'"
data1 = ('Stockable',)
cursor.execute(sql1, data1)
dbcon.commit()
print("Rows affected: ", cursor.rowcount)
dbcon.close()

You might also like