0% found this document useful (0 votes)
159 views

Program File

The document describes 5 programs related to Python functions and concepts. Program 1 creates a simple calculator using functions for addition, subtraction, multiplication, division and exponents. Program 2 creates a temperature converter using functions to convert between Celsius and Fahrenheit. Program 3 creates a geometry calculator using functions within packages to calculate properties of 2D and 3D shapes. Program 4 includes programs to calculate the factorial of a number and Fibonacci series using recursive functions. Program 5 includes programs to test if a number is prime and to convert currency between dollars and rupees using functions.

Uploaded by

Dinesh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
159 views

Program File

The document describes 5 programs related to Python functions and concepts. Program 1 creates a simple calculator using functions for addition, subtraction, multiplication, division and exponents. Program 2 creates a temperature converter using functions to convert between Celsius and Fahrenheit. Program 3 creates a geometry calculator using functions within packages to calculate properties of 2D and 3D shapes. Program 4 includes programs to calculate the factorial of a number and Fibonacci series using recursive functions. Program 5 includes programs to test if a number is prime and to convert currency between dollars and rupees using functions.

Uploaded by

Dinesh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 58

PROGRAM 1

OBJECTIVE: To create a program for a simple calculator in python.

CONCEPT USED: Use of Function and python loops.

SOURCE CODE:
PYTHON_Calculator.py

#Addition

def add(a,b):

return a+b

#Subtract

def sub(a,b):

return a-b

#Multiply

def mul(a,b):

return a*b

#Divide

def div(a,b):

return a/b

#Exponents

def exp(a,b):

return a**b
choice=int(input("Select operation \n 1.Addition \n 2.Subtract \n 3.Multiply \n 4.Divide \n
5.Exponents \n 6.Exit \n"))

while choice!=6:

if choice>6:

choice=int(input("INVALID OPERATION!!!!! \n Select operation AGAIN!! \n 1.Addition \n


2.Subtract \n 3.Multiply \n 4.Divide \n 5.Exponents \n 6.Exit \n"))

x=int(input("Enter 1st no. "))

y=int(input("Enter 2nd no. "))

if choice==1:

print("Sum of these 2 numbers is",add(x,y))

elif choice==2:

print("Subtraction of these numbers is",sub(x,y))

elif choice==3:

print("multiplication of these numbers is ",mul(x,y))

elif choice==4:

print("Division of these numbers is ",div(x,y))

elif choice==5:

print("Exponent of these numbers is ",exp(x,y))

else:

break

choice=int(input("Select operation AGAIN\n 1.Addition \n 2.Subtract \n 3.Multiply \n 4.Divide \n


5.Exponents \n 6.Exit \n"))

else:

print("BYE BYE!!!")
SCREENSHOT:

CONCLUSION:
The program is successfully executed.
PROGRAM 2
OBJECTIVE: To create a program for a simple Temperature converter in python.

CONCEPT USED: Use of Function and python loops.

SOURCE CODE:

Functions:
temp.py

#FROM CELSIUS to FEHRENHEIT

def in_f(c):

return (c*9//5)+32

#FROM FEHRENHEIT TO CELSIUS

def in_c(f):

return (f-32)*5//9

Program:
PYTHON_tempconverter.py

import temp

choice=int(input("Choose from below to be converted: \n 1.Celsius \n 2.Fahrenheit \n 3.Exit \n"))

while choice!=3:

if choice>3:

choice=int(input("Choose a valid operation \n 1.Celsius \n 2.Fahrenheit \n 3.Exit\n"))

if choice==1:

c=float(input("Enter temperature in CELSIUS to be converted :- "))

print("Temperature in FAHRENHEIT is ",temp.in_f(c))

elif choice==2:

f=float(input("Enter temperature in FAHRENHEIT to be converted :- "))


print("Temperature in CELSIUS is ",temp.in_c(f))

else:

break

choice=int(input("Choose AGAIN \n 1.Celsius \n 2.Fahrenheit \n 3.Exit\n"))

else:

print("SEE YOU SOON!!!!")

SCREENSHOT:

CONCLUSION:
The program is successfully executed.
PROGRAM 3
OBJECTIVE: To create packages in python and create a program for simple Mensuration
calculations with the use of user-defined packages.

CONCEPT USED: Use of Function, python loops and recursion.

SOURCE CODE:

Functions:

{a}For 2 Dimensional figures.


Function_2D.py

#RECTANGLE

def rectangle_area(l,b):

return l*b

def rectangle_perimeter(l,b):

return 2*(l+b)

#SQUARE

def square_area(s):

return s*s

def square_perimeter(s):

return 4*s

#TRIANGLE

def triangle_area(b,h):

return 1/2*b*h

def triangle_perimeter(a,b,c):

return a+b+c

#CIRCLE
def circle_area(r):

return 3.14*r**2

def circle_perimeter(r):

return 2*3.14*r

{b}For 3 Dimensional figures.


Function_3D.py

#CUBE

def cube_area(a):

return 6*a**2

def cube_volume(a):

return a**3

#CUBOID

def cuboid_area(l,b,h):

return 2*(l*b+b*h+h*l)

def cuboid_volume(l,b,h):

return l*b*h

#CYLINDER

def cylinder_area(h,r):

return 2*3.14*r*(r+h)

def cylinder_volume(h,r):

return 2*3.14*r*h

#CONE

def cone_area(l,r):

return 3.14*r*l

def cone_volume(l,r,h):

return 1/3*3.14*r**2*h

#SPHERE
def sphere_area(r):

return 4*3.14*r**2

def sphere_volume(r):

return 4/3*3.14*r**3

Program:
PYTHON_Mensuration_Calculator.py

a=int(input("Choose a dimension \n(1).2D \n(2).3D \n OR\n(3).EXIT \n "))

while a!=3:

if a==1:

from Mensuration.Two_D import function_2D

b=int(input("Choose an operation: \n <1>.Perimeter \n <2>.Area \n "))

c=int(input("Choose shape of a figure from below\n [1].SQUARE\n [2].RECTANGLE\n

[3].CIRCLE\n [4].TRIANGLE\n "))

if c==1:

x=int(input("Enter side of a square: "))

if b==1:

print("Peremeter of square is: ",function_2D.square_perimeter(x))

else:

print("Area of square is: ",function_2D.square_area(x))

elif c==2:

x=int(input("Enter length of a rectangle: "))

y=int(input("Enter breadth of a rectangle: "))

if b==1:

print("Peremeter of rectangle is: ",function_2D.rectangle_perimeter(x,y))

else:

print("Area of rectangle is: ",function_2D.rectangle_area(x,y))

elif c==3:

x=int(input("Enter radius of a circle: "))


if b==1:

print("circumferene of circle is: ",function_2D.circle_perimeter(x))

else:

print("Area of circle is: ",function_2D.circle_area(x))

elif c==4:

x=int(input("Enter length of 1st side of a triangle: "))

y=int(input("Enter length of 2st side of a triangle: "))

z=int(input("Enter length of 3st side of a triangle: "))

h=int(input("Enter height of a triangle: "))

if b==1:

print("Perimeter of triangle is: ",function_2D.triangle_perimeter(x,y,z))

else:

print("Area of triangle is: ",function_2D.triangle_area(y,h))

else:

break

print()

a=int(input("Choose a dimension AGAIN! \n(1).2D \n(2).3D \n OR\n(3).EXIT\n "))

elif a==2:

from Mensuration.Three_D import function_3D

b=int(input("Choose an operation:\n <1>.Volume\n <2>.Area\n "))

c=int(input("Choose shape of a figure from below\n [1].CUBE\n [2].CUBOID\n

[3].CYLINDER\n [4].CONE\n [5].SPHERE\n "))

if c==1:

x=int(input("Enter side of a cube: "))

if b==1:

print("Volume of cube is: ",function_3D.cube_volume(x))

else:

print("Area of cube is: ",function_3D.cube_area(x))


elif c==2:

x=int(input("Enter length of a cuboid: "))

y=int(input("Enter breadth of a cuboid: "))

z=int(input("Enter height of a cuboid: "))

if b==1:

print("volume of cuboid is: ",function_3D.cuboid_volume(x,y,z))

else:

print("Area of cuboid is: ",function_3D.cuboid_area(x,y,z))

elif c==3:

x=int(input("Enter radius of a cylinder: "))

y=int(input("Enter height of a cylinder: "))

if b==1:

print("Volume of cylinder is: ",function_3D.cylinder_volume(y,x))

else:

print("Area of cylinder is: ",function_3D.cylinder_area(y,x))

elif c==4:

x=int(input("Enter length of a cone: "))

y=int(input("Enter heigth of a cone: "))

z=int(input("Enter radius of a cone: "))

if b==1:

print("Volume of cone is: ",function_3D.cone_volume(x,z,y))

else:

print("Area of cone is: ",function_3D.cone_area(x,z))

elif c==5:

x=int(input("Enter radius of a sphere: "))

if b==1:

print("Volume of sphere is: ",function_3D.sphere_volume(x))

else:
print("Area of sphere is: ",function_3D.sphere_area(x))

else:

break

print()

a=int(input("Choose a dimension AGAIN!\n (1).2D\n (2).3D\n OR\n (3).EXIT\n "))

else:

print("SEE YOU SOON!!!!!!")

SCREENSHOTS:

P.T.O
CONCLUSION:
The program is successfully executed.
PROGRAM 4
OBJECTIVE: (A) To create a program for calculating factorial of a given number.

(B) To create a program for Fibonacci series using recursion.

CONCEPT USED: Use of Function, python loops and recursion


DESCRIPTION:- A function is said to be recursive if it calls itself.
In this program both are direct recursion.
ADVANTAGES:-
1. Recursion is more elegant and requires a lesser no. of variables which makes the program
short and clean.
2. Recursion can be made to replace complex nesting code since we don’t have to call the
program, again and again, to do so the same task as it calls itself.
DISADVANTAGES:-
1. It is comparatively difficult to think of the logic of a recursive function.
2.It also sometimes becomes difficult to debug a recursive code.

SOURCE CODE:

Program (A):
Factorial.py

def factorial(n):

if n==1:

return 1

else:

return n*factorial(n-1)

a=int(input("Enter number to be factorialed: "))

print(factorial(a))
Program (B):
fibonacci_series.py

def fibo(n):

if n<=1:

return n

else:

return fibo(n-1)+fibo(n-2)

a=int(input("Enter number of terms to be in fibonaci series: "))

for i in range(a):

print(fibo(i))

SCREENSHOT (A):

P.T.O
SCREENSHOT (B):

CONCLUSION:
The program is successfully executed.
PROGRAM 5
OBJECTIVE:
(A). Write a function that takes one argument (a positive integer) and reports if the argument is prime
or not. Write a program that invokes this function.
(B). Write a function that takes amount-in-dollars and dollar-to-rupee conversion price; it then returns
the amount converted to rupees. Create the function in both void and non-void form

CONCEPT USED: Use of Function, python loops.

SOURCE CODE:

Program (A):
prime_test.py

def test_prime(n):

if n==1:

return "it is not prime"

elif n==2:

return "It is prime"

else:

for x in range(2,n):

if n%x==0:

return "It is not prime"

return "It is prime"

for j in range(0,5):

a=int(input("Enter no. to be tested: "))

print(test_prime(a))
Program (B):
dollar_to_rupee_converter.py

#void version

def usd_to_inr(amt):

exc=71.08

print("Rs",amt*exc)

#non-void version

def usd_to_inr2(amt):

exc=71.08

return amt*exc

usd_to_inr(100)

print("Rs",usd_to_inr2(200)) #value is being returned


SCREENSHOT (A):

SCREENSHOT (B):

CONCLUSION:
The program is successfully executed.
PROGRAM 6
OBJECTIVE:
(A). Write a program that inputs a 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.
(B). Write a number to implement ‘guess a number’ game. Python generates a number
randomly in the range[10,50]. The user is given five chances to guess a number in the range 10
<= number <= 50.
If the user’s guess matches the number generated, Python displays ‘You win’ and the loop
terminates without completing the five iterations.
If, however, cannot guess the number in five attempts, Python displays ‘You lose’.

CONCEPT USED: Use of string Functions and ‘random’ library of python.

SOURCE CODE:

Program (A):
String_encryptor _test.py

def encrypt(str,enkey):

return enkey.join(str)

def decrypt(str,enkey):

return str.split(enkey)

#main program

mainString=input("Enter main string: ")

encryptStr=input("Enter encryption key: ")

enStr=encrypt(mainString,encryptStr)

decStr=decrypt(enStr,encryptStr)

orig_decStr="".join(decStr)
print("The encrypted string is: ",enStr)

print("String after decryption is: ",orig_decStr)

Program (B):
guess_a_number_game.py

import random

guessesTaken = 0

myName = input('Hello! What is your name?')

number = random.randint(10,50)

print('Well',myName,'I am thinking of a number between 10 and 50.')

while guessesTaken<5:

guess = int(input('Take a guess.'))

guessesTaken+=1

if guess < number:

print('Your guess is too low.')

if guess > number:

print('Your guess is too high.')

if guess == number:

break

if guess == number:

print('Good job',myName,'! You guessed my number in ',guessesTaken,'guesses!')

elif guess != number:

print('Nope. The number I was thinking of was ',number)


SCREENSHOT (A):

SCREENSHOT (B):

CONCLUSION:
The program is successfully executed.
PROGRAM 7
OBJECTIVE:
(A). Write a program to get http request from url www.ted.com and open it from within your
program.
(B). Write a program to count the words “to” and “the” present in a text file “Poem.txt”

CONCEPT USED: Use of Function, python loops and count function.

SOURCE CODE:

Program (A):
http_req_url.py

import urllib

import webbrowser

weburl=url.request.urlopen('http://www.ted.com/')

html=weburl.read()

data=weburl.geturl()

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 info() returned:\n",inf)

print("Now opening the url",url)

webbrowser.open_new(url)
Program (B):
count_words_from_text.py

f=open('Poem.txt','r')

c_to=0

c_the=0

for line in f:

c_to+=line.count('to')

c_the+=line.count('the')

print(c_to)

print(c_the)

f.close()

Poem.txt

Feeling so out-of-place.

What my body wants and needs, this isn't me.

I'm always longing for someplace else and now I realize,

I want a place to be free.

These streets, this town, this nation are not my home.

No wonder I can't identify with what isn't my own.

I'm never satisfied, I will never be satisfied.

What I want can only be found inside my mind.

Nothing I seek is in what I buy.

No wonder that by money I was never mystified.

My home is where what I believe without seeing lies.

What I feel in my bones is the bare bones of my house.

What can I do to make it real?


What can I feel, and does what I feel arouse the walls from the floor,

or the roof from the ground?

I have been living in so many fractions, in a room of ideas, but now

I want to build my world in actions.

I need to see my Walden come alive.

Before my flesh comes undone, allow me and my home to arrive.

SCREENSHOT (A):
SCREENSHOT (B):

CONCLUSION:
The program is successfully executed.
PROGRAM 8
OBJECTIVE:
(A). Create a file sports.dat contains information in the following format: Event ~ Participant.
Write a function that would read contents from the file sports.dat and creates a file named
Atheletic.dat copying only those records from sports.dat where the event name is “Atheletics”
(B). Write a recursive function to print a string backwards.

CONCEPT USED: Use of Function, python loops.

SOURCE CODE:

Program (A):
copying_records.py

#creating sports.dat

f1=open("sports.dat","w")

f2=open("atheletics.dat","w")

f1.write("EVENT ~ PARTICIPENTS\n")

count=int(input("How many students are there in sports: "))

for i in range(count):

e=input("Enter event name: ")

p=input("Enter participent's name: ")

rec=e+" ~ "+p+'\n'

f1.write(rec)

f2.write("EVENT ~ PARTICIPENTS\n")

f1=open("sports.dat","r")

for line in f1:

words=line.split(" ")

if words[0]=="Atheletics":
f2.write(line)

f1.close()

f2.close()

Program (B):

reverse_string.py

def recursiveReverse(str,i=0):

n=len(str)

if i==n//2:

return

str[i],str[n-i-1]=str[n-i-1],str[i]

recursiveReverse(str,i+1)

# converting string to list

# because strings do not support

# item assignment

org_str=input("Enter string that has to be reversed: ")

org_lst=list(org_str)

recursiveReverse(org_lst)

# converting list to string

rev_str=''.join(org_lst)

print(rev_str)
SCREENSHOT (A):

SCREENSHOT (B):

CONCLUSION:
The program is successfully executed.
PROGRAM 9
OBJECTIVE:
(A). Write a recursive function to calculate the gcd of given two numbers
(B). Write a recursive code to compute factorial of a given number.
(C). Write a recursive function to implement binary search algorithm.

CONCEPT USED: Making recursive functions with a base condition.

SOURCE CODE:

Program (A):
GCD_recursively.py

def gcd(p,q):

if q==0:

return p

return gcd(q,p%q)

print("Greatest common divisor of numbers 1440 and 408 is ",gcd(1440,408))

print()

print()

print("Greatest common divisor of numbers 5444 and 372 is ",gcd(5444,372))

Program (B):
factorial_recursively.py

def factorial(n):

if n<2:

return 1

return n*factorial(n-1)

for i in range(3):

n=int(input("Enter a number: "))


print("Factorial of",n,"is",factorial(n))

print()

Program (C):
Binary_search_recursively.py

def bin_ser(ar,key,low,high):

if low>high:

return -1

mid=int((low+high)//2)

if key==ar[mid]:

return mid

elif key<ar[mid]:

high=mid-1

return bin_ser(ar,key,low,high)

else:

low=mid+1

return bin_ser(ar,key,low,high)

#__main__

ary=eval(input("Enter an array: "))

#sorted array

item=int(input("Enter search item: "))

res=bin_ser(ary,item,0,len(ary)-1)

if res>=0:

print(item,"FOUND at position ",res+1)

else:

print("Sorry!",item,"NOT FOUND in array")


SCREENSHOT (A):

SCREENSHOT (B):

SCREENSHOT (C):

CONCLUSION:
The program is successfully executed.
PROGRAM 10
OBJECTIVE:
Create an array in the range 1 to 20 with values 1.25 apart. Another array contains the log
values of the elements in the first array.
(A). Simply plot the two arrays first vs second in a line chart.
(B). In the plot of first vs second array, specify the x-axis(containing first array’s values) title
as ‘Random Values’ and y-axis title as ‘Logarithm Values’
(C). Create a third array that stores the Cos values of first array and then plot both the second
and third arrays vs first array. The cos values should be plotted with a dash-dotted line.
(D). Change the marker type as circle with blue color in second array.
(E). Only mark the data points as this: second array data points as blue small diamonds, third
array data points as black circles.

CONCEPT USED: Using NumPy Arrays and its useful functions. Creating charts with
matplotlib library’s pyplot interface.

SOURCE CODE:
Ploting_two_ary.py

(A).
import numpy as np

import matplotlib.pyplot as plt

a=np.arange(1,20,1.25)

b=np.log(a)

plt.plot(a,b)

(B).
plt.plot(a,b)

plt.xlabel("Random Values")

plt.ylabel("Logarithm Values")

plt.show()
(C).
c=np.cos(a)

plt.plot(a,b)

plt.plot(a,c,linestyle="dashdot")

plt.show()

(D).
c=np.cos(a)

plt.plot(a,b)

plt.plot(a,c,'bo',linestyle='dashdot')

plt.show()

(E).
c=np.cos(a)

plt.plot(a,b,'bd')

plt.plot(a,c,'ro')

plt.show()
SCREENSHOT:

(A).

(B).

(C).
(D).

(E).

CONCLUSION:
The program is successfully executed.
PROGRAM 11
OBJECTIVE:
Carefully go through the average data for Mumbai city from the Indian Met Department.
Jan Feb Mar Apr May Jun
High 31.1 31.3 32.8 33.2 33.6 32.4
Temp
Low 17.3 18.2 21.4 24.2 27.0 26.6
Temp
Rainfall 0.3 0.4 0.0 0.1 11.3 493.1

Relatie 69 67 69 71 70 80
Humiity

(A). Plot the four sequences on a bar chart where red color shows the HighTemp, blue colour
shoes the LowTemp, olive colour depicts the Rainfall sequence and silver colour depicts the
RelHumidity sequence.
(B). Make width of these bars as 0.28
(C). Change the x-ticks such that they display the month numbers in place of month names
(D). Add legends for these providing meaningful labels for these sequences
(E). Give appropriate title for the chart and axes
(F). Save the chart as “multibar.pdf”

CONCEPT USED: Using NumPy Arrays and its useful functions. Creating charts with
matplotlib library’s pyplot interface.

SOURCE CODE:
Bar_graph.py

(A).
import numpy as np

import matplotlib.pyplot as plt

a=['Jan','Feb','Mar','Apr','May','Jun']

A=np.arange(len(a))

B=[[31.1,31.3,32.8,33.2,33.6,33.4],[17.3,18.2,21.2,24.2,27.0,26.6],[0.3,0.4,0.0,0.1,11.3,49.3],
[69.,67.,69.,71.,70.,80.]]
plt.bar(A+0.00,B[0],color='red',width=0.28,label='High Temperature')

plt.bar(A+0.28,B[1],color='blue',width=0.28,label='LowTemperature')

plt.bar(A+0.56,B[2],color='olive',width=0.28,label='Rainfall')

plt.bar(A+0.81,B[3],color='silver',width=0.28,label='Relative Humidity')

plt.legend(loc='upper left')

plt.xlabel("Month numbers")

plt.ylabel("Measurements")

plt.show()

SCREENSHOT:

CONCLUSION:
The program is successfully executed.
PROGRAM 12
OBJECTIVE:
Write to create a pie for sequence con = [23.4, 17.8, 25, 34, 40] for Zones = [‘East’, ‘West’,
‘North’, ‘South’, ‘Central’]
(A) Show North zone’s value exploded
(B). Show % contribution for each zone
(C). The pie chart should be circular.

CONCEPT USED: Creating charts with matplotlib library’s pyplot interface.

SOURCE CODE:
pie_chart.py

import matplotlib.pyplot as plt

con=[23.4,17.8,25,34,40]

zones=['East','West','North','South','Central']

plt.axis("equal")

plt.pie(con,labels=zones,explode=[0,0,0.2,0,0],autopct="%1.2f%%")

plt.show()

SCREENSHOT:

CONCLUSION:
The program is successfully executed.
PROGRAM 13
OBJECTIVE:
Write a menu driven program to do the following tasks:
(A). Traverse through a sorted list
(B). Search for an element in a sorted list by implementing Linear Search algorithm

CONCEPT USED: Some basic concepts of python.

SOURCE CODE:

Program (A):
traversal.py

def traverse(AR):

size=len(AR)

for i in range(size):

print(AR[i],end=' ')

#__main__

size=int(input("Enter the size of linear list: "))

AR=[None]*size

print("Enter elements for the Linear list: ")

for i in range(size):

AR[i]=int(input("Element "+str(i)+" :"))

print("Traverseing the list: ")

traverse(AR)
Program (B):
Linear_search.py

def lsearch(ar,item):

i=0

while i<len(ar) and ar[i]!=item:

i+=1

if i<len(ar):

return i

else:

return False

n=int(input("Enter desired linear-list size: "))

print("\nEnter elements for Linear List\n ")

ar=[0]*n

for i in range(n):

ar[i]=int(input("Element "+str(i)+" :"))

item=int(input("\nEnter Element to be searched for....."))

index=lsearch(ar,item)

if index:

print("\nElement found at index: ",index,",Position:",index+1)

else:

print("\nSorry!! given element could not be found.")


SCREENSHOT (A):

SCREENSHOT (B):

CONCLUSION:
The program is successfully executed.
PROGRAM 14
OBJECTIVE:
Write a menu driven program to do the following tasks:
(A). Insert an element in a sorted list
(B). Delete an element from a sorted list

CONCEPT USED: Some basic concepts of python and bisect module.

SOURCE CODE:

Program (A):
element_insertion.py

n=int(input("Enter desired linear-list size: "))

print("\nEnter elements for Linear List\n ")

ar=[0]*n

for i in range(n):

ar[i]=int(input("Element "+str(i)+" :"))

item=int(input("\nEnter Element to be inserted....."))

import bisect

ind=bisect.bisect(ar,item)

bisect.insort(ar,item)

print(ar)
Program (B):
element_deletion.py

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

n=int(input("Enter desired linear-list size: "))

print("\nEnter elements for Linear List\n ")

ar=[0]*n

for i in range(n):

ar[i]=int(input("Element "+str(i)+" :"))

item=int(input("\nEnter Element to be deleted....."))

pos=bsearch(ar,item)

if pos:

del ar[pos]

print("List after deleting ",item,"is")

print(ar)
else:

print("Sorry!! no such element in the list")

SCREENSHOT (A):

SCREENSHOT (B):
CONCLUSION:
The program is successfully executed.
PROGRAM 15
OBJECTIVE:
Use a list comprehension to create a list, CB4. The comprehension should consist of the
cubes of the numbers 1 through 10 only if the cube is evenly divisible by four. Finally, print
that list to the console. Note that in this case, the cubed number should be evenly divisible by
4, not the original number

CONCEPT USED: Use of list comprehensions.

SOURCE CODE:
CB4.py

CB4=[i**3 for i in range(1,11) if (i**3)%4==0]

print(CB4)

SCREENSHOT:

CONCLUSION:
The program is successfully executed.
PROGRAM 16
OBJECTIVE: Write a menu based program to implement Stack operations.

CONCEPT USED: Creating functions and implementing them & some basics of python.

SOURCE CODE:
stack.py

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):

return"Stack empty"

else:

top=len(stk)-1

print("\n",stk[top],"<-top")

for a in range(top-1,-1,-1):

print(stk[a])

#__main__

stack=[]

top=None

while True:

print("STACK OPERATIONS\n1. Push\n2. Pop\n3. Peek\n4. Display stack\n5. 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("\nPopped item is ",item)

elif ch==3:

item=peek(stack)

if item=="Underflow":

print("Underflow! stack is empty")

else:

print("\nTopmost item is ",item)

elif ch==4:

display(stack)

elif ch==5:

break

else:

print("\nINVALID choice!!")
SCREENSHOT:

CONCLUSION:
The program is successfully executed.
PROGRAM 17
OBJECTIVE: Write a menu based program to implement Queue operations.

CONCEPT USED: Creating functions and implementing them & some basics of python.

SOURCE CODE:
queue.py

def cls():

print("\n"*2)

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):

return"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__

queue=[]
front=None

while True:

cls()

print("QUEUE OPERATIONS\n1. Enqueue\n2. Dequeue\n3. Peek\n4. Display queue\n5.


Exit")

ch=int(input("Enter your choice(1-5): "))

if ch==1:

item=int(input("Enter item: "))

enqueue(queue,item)

elif ch==2:

item=dequeue(queue)

if item=="Underflow":

print("Underflow! Queue is empty")

else:

print("\nDequeue-ed item is ",item)

elif ch==3:

item=peek(queue)

if item=="Underflow":

print("Queue is empty")

else:

print("\nFrontmost item is ",item)

elif ch==4:

display(queue)

elif ch==5:

break

else:

print("\nINVALID choice!!")
SCREENSHOT

CONCLUSION:
The program is successfully executed.
PROGRAM 18
OBJECTIVE: Create a Django based web application.

CONCEPT USED: Creating functions and implementing them & some basics of python.

SOURCE CODE:
queue.py

def cls():

print("\n"*2)

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):

return"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__

queue=[]
front=None

while True:

cls()

print("QUEUE OPERATIONS\n1. Enqueue\n2. Dequeue\n3. Peek\n4. Display queue\n5.


Exit")

ch=int(input("Enter your choice(1-5): "))

if ch==1:

item=int(input("Enter item: "))

enqueue(queue,item)

elif ch==2:

item=dequeue(queue)

if item=="Underflow":

print("Underflow! Queue is empty")

else:

print("\nDequeue-ed item is ",item)

elif ch==3:

item=peek(queue)

if item=="Underflow":

print("Queue is empty")

else:

print("\nFrontmost item is ",item)

elif ch==4:

display(queue)

elif ch==5:

break

else:

print("\nINVALID choice!!")
SCREENSHOT

CONCLUSION:
The program is successfully executed.

You might also like