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

CS Practicals-1 (1) - 2

The document contains 14 programming problems related to recursion, functions, lists, strings, file handling, database connectivity and sorting algorithms. Each problem has the problem statement, sample code as input and expected output. The problems cover concepts like recursion to find factorial, Fibonacci series, sum of list elements; functions; file handling like reading and writing to files, counting words; database operations; plotting functions; sorting algorithms like bubble sort, insertion sort.
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)
106 views37 pages

CS Practicals-1 (1) - 2

The document contains 14 programming problems related to recursion, functions, lists, strings, file handling, database connectivity and sorting algorithms. Each problem has the problem statement, sample code as input and expected output. The problems cover concepts like recursion to find factorial, Fibonacci series, sum of list elements; functions; file handling like reading and writing to files, counting words; database operations; plotting functions; sorting algorithms like bubble sort, insertion sort.
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

Practical No.

1(a)
Write a program to recursively find the
factorial of a number.

Code:
n=int(input("enter no :"))
result=fact(n)
print("the factorial of no is",result)
def fact(n):
if n<2:
return 1
else:
return n*fact(n-1)
Output:
Practical No. 1(b)
write a program to recursively find nth
Fibonacci number.

Input:
def fib(n):
if n==1:
return 0
elif n==2:
return 1
else:
return fib(n-1)+fib(n-2)
n=int(input("enter last term required:"))
for i in range(1,n+1):
print(fib(i),end=',')
print("......")
Output:
Practical No. 2(a)
Write a recursively code to find the
sum of all element of a list.

Input:

def lisum(list1,b):
if b<0:
return 0
else:
return list1[b]+lisum(list1,b-1)
list1=eval(input("Enter the elements in a list"))
length=len(list1)
total=lisum(list1,length-1)
print ("sum of elements in the list is...",total)
Output:
Practical No. 2(b)
Write a recursively python program to
test if the string is palindrome or not.
Input:

def P(L,M):
if M==0:
return L[0]
if M>0:
return L[M]+P(L,M-1)
Q=input("enter a string:")
R=P(Q,len(Q)-1)
if Q==R:
print("string is palindrome:")
else:
print("string is not palindrome:")
Output:
Practical No. 3
Write a recursive code in python to
perform binary search.
Input:
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 = [12,15,21,25,28,32,33,36,43,45]
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:
Practical No. 4
Write a python code to open web page
using url library.
INPUT:
import urllib.request
import webbrowser
weburl=urllib.request.urlopen('http://www.google.com/')
html=weburl.read()
data=weburl.getcode()
url=weburl.geturl()
hd=weburl.headers
inf=weburl.info()
print ("The url is ",url)
print("HTTP status code is :",data)
print("headers returned:\n",hd)
print("The unfo() returned:\n",inf)
print("Now opening the url",url)
webbrowser.open_new(url)
OUTPUT:
Practical No. 5
Write a program to read a
textfile”myfile.txt”line by line and print
it.
Input:

fh=open("myfile.txt",'r')
while True:
a=fh.readline()
print(a)
if a=="":
break
fh.close()
Output:
Practical No. 6
Write a program to remove all the lines
that contains the character ‘a’ in a file and
write it into another file.
Input:
read1=open(r'C:\Users\lenovo\AppData\Local\Programs\Python\
Python37-32\file2.txt','r')
write1=open(r'C:\Users\lenovo\AppData\Local\Programs\Python
\Python37-32\filew.txt','w')
b=''
while True:
b=read1.readline( )
if 'a' in b:
write1.write(b)
if b=="":
break
print ("file written")
read1.close( )
write1.close( )
Output:
Practical No. 7
Write a program to count the word
“to”and “the” present in textfile
“myfile.txt”.
Input:
fh=open("myfile.txt","r")
line=""
c=0
c1=0
while True :
line=fh.readline( )
if line == "":
break
a=line.split( )
for x in a:
if x =="to":
c=c+1
if x=="the":
c1=c1+1
print (“Number of to=”,c)
print (“Number of the=”,c1)
Text File:

Output:
Practical No. 8
Write a program in python that accepts a
filename and reports the file longest line.
Input:

def stats(fh):
longest=" "
line=" "
while True:
line=fh.readline()
if line=="":
break
elif len(line)>len(longest):
longest=line
print(longest)
print(len(longest))
fh.close()
a=input("enter file name")
fil=open(a,'r')
stats(fil)
Practical No. 9(a)
A function that take a number as
argument and calculate cube for it.The
function does not return a value.If there is
no value passed to the function in function
call,the function should calculate cube of
2.
Input:

def func(num=2):
print ("The cube is ",num*num*num)
num=int(input("Enter a no."))
func(num)
func()
Output:
Practical No. 9(b)
(b).A function that take two number as argument
and return True if both the argument are equal
otherwise Flase.

Input:
def func(str1,str2):
if str1==str2:
return True
else:
return False
str1=input("Enter 1st character")
str2=input("Enter 2nd character")
result=func(str1,str2)
print (result)
Output:
Practical No. 10
Write a python database connectivity script
that deletes records from Garments table of
‘Mydata’ database having size ‘XL’.

Table:

Gcode Gname Size Colour Price


111 T shirt XL Red 1400
112 Jeans L Blue 1600
113 Shirt M Black 1100
114 Ladies XL Blue 4000
jacket
115 Trouser L Brown 15000
116 L.Top L pink 1200
Coding:
importmysql.connector
mycon=mysql.connector.connect(host='localhost',user='root',p
asswd='admin',database='mydata')
ifmycon.is_connected():
print ("mysql connected to python successfully")
cursor=mycon.cursor()
cursor.execute("delete from garments where size='XL'")
print ("available records")
cursor.execute("select * from garments")
data=cursor.fetchall()
for row in data:
print (row)
print ("record deleted successfully")
Output:
Practical No. 11
Write a python database connectivity script to
display all the records of soft drink table from
‘Mydata’ database.
Coding:
importmysql.connector
mycon=mysql.connector.connect(host='localhost',user='root',p
asswd='admin',database='mydata')
ifmycon.is_connected():
print ("mysql is conntected successfully to python")
cursor=mycon.cursor()
cursor.execute("select * from softdrinks")
data=cursor.fetchall()
for row in data:
print (row)
Output:
Practical No.12
Write a python program to plot function -
y=x2 using pyplot on matplotlib libearies.

Coding:

importnumpy as np
importmatplotlib.pyplot as plt
x=eval(input('enter a list'))
y=[]
y=[(a*a) for a in x]
plt.plot(x,y,'m',linewidth=2,marker='p',markersize=8)
Output:
Practical No. 13
Write a python code using function to
perform bubble sort.

Coding:
def bubble(lst):
n=len(lst)
for i in range(n):
for j in range(0,n-i-1):
iflst[j]>lst[j+1]:
lst[j],lst[j+1]=lst[j+1],lst[j]
print("lst after sorting:",lst)

lst1=eval(input("enter a lst"))
bubble(lst1)
Output:
Practical No. 14
Q. Write a python code to arrange the
elements in ascending order using insertion
sort.
CODING

lst=eval(input("enter the lst"))


n=len(lst)
for i in range(1,len(lst)):
key=lst[i]
j=i-1
while j>=0 and key<lst[j]:
lst[j+1]=lst[j]
j=j-1
else:
lst[j+1]=key
print("lst after sorting:", lst)
Output:
Session 2019-20
Computer Science Practical File

Submitted to- Akanksha Dhami


Submitted by: Shivank Chaudhary
Roll NO:

You might also like