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

PRACTICAL LIST XII CS Solutions

The document provides source code solutions for 22 problems involving basic Python programming concepts like conditional statements, loops, functions, recursion, data structures (lists, stacks, queues) and plotting graphs. The problems cover topics such as checking prime and palindrome numbers, calculating compound interest and factorial, ASCII conversions, plotting graphs for mathematical functions and real-world data, and implementing sorting and searching algorithms. Menu-based programs are provided to demonstrate stack and queue operations in Python.

Uploaded by

Jayesh Deshmukh
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)
169 views

PRACTICAL LIST XII CS Solutions

The document provides source code solutions for 22 problems involving basic Python programming concepts like conditional statements, loops, functions, recursion, data structures (lists, stacks, queues) and plotting graphs. The problems cover topics such as checking prime and palindrome numbers, calculating compound interest and factorial, ASCII conversions, plotting graphs for mathematical functions and real-world data, and implementing sorting and searching algorithms. Menu-based programs are provided to demonstrate stack and queue operations in Python.

Uploaded by

Jayesh Deshmukh
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/ 9

PRACTICAL NO.

OBJECTIVE & SOLUTION

1. Write a program in python to check a number whether it is prime or not.

SOURCE CODE:

num=int(input("Enter the number: "))

for i in range(2,num):

if num%i==0:

print(num, "is not prime number")

break;

else:

print(num,"is prime number")

2. Write a program to check a number whether it is palindrome or not.

SOURCE CODE:

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

n=num res=0

while num>0:

rem=num%10

res=rem+res*10

num=num//10

if res==n:

print("Number is Palindrome")

else:

print("Number is not Palindrome")

3. Write a program to calculate compound interest.

SOURCE CODE:

p=float(input("Enter the principal amount : "))

r=float(input("Enter the rate of interest : "))

t=float(input("Enter the time in years : "))

x=(1+r/100)**t

CI= p*x-p print("Compound interest is : ", round(CI,2))


4. Write a program to display ASCII code of a character and vice versa.

SOURCE CODE:

var=True

while var:

choice=int(input("Press-1 to find the ordinal value of a character \nPress-2 to find a character of a


value\n"))

if choice==1:

ch=input("Enter a character : ")

print(ord(ch))

elif choice==2:

val=int(input("Enter an integer value: "))

print(chr(val))

else:

print("You entered wrong choice")

print("Do you want to continue? Y/N")

option=input()

if option=='y' or option=='Y':

var=True

else:

var=False

5. Write a program to input a character and to print whether a given character is an alphabet, digit or any other
character.

SOURCE CODE:

ch=input("Enter a character: ")

if ch.isalpha():

print(ch, "is an alphabet")

elif ch.isdigit():

print(ch, "is a digit")

elif ch.isalnum():

print(ch, "is alphabet and numeric")

else:
print(ch, "is a special symbol")

6. Write a program to calculate the factorial of an integer using recursion.

SOURCE CODE:

def factorial(n):

if n == 1:

return n

else:

return n*factorial(n-1)

num=int(input("enter the number: "))

if num < 0:

print("Sorry, factorial does not exist for negative numbers")

elif num == 0:

print("The factorial of 0 is 1")

else:

print("The factorial of ",num," is ", factorial(num))

7. Write a program to print fibonacci series using recursion.

SOURCE CODE:

def fibonacci(n):

if n<=1:

return n

else:

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

num=int(input("How many terms you want to display: "))

for i in range(num):

print(fibonacci(i)," ", end=" ")

8. Write a program for binary search.

SOURCE CODE:
def Binary_Search(sequence, item, LB, UB):

if LB>UB:

return -5 # return any negative value

mid=int((LB+UB)/2)

if item==sequence[mid]:

return mid

elif item<sequence[mid]:

UB=mid-1

return Binary_Search(sequence, item, LB, UB)

else:

LB=mid+1

return Binary_Search(sequence, item, LB, UB)

L=eval(input("Enter the elements in sorted order: "))

n=len(L)

element=int(input("Enter the element that you want to search :"))

found=Binary_Search(L,element,0,n-1)

if found>=0:

print(element, "Found at the index : ",found)

else:

print("Element not present in the list")

9. Write a recursive python program to test if a string is palindrome or not.

SOURCE CODE:

def isStringPalindrome(str):

if len(str)<=1:

return True

else:

if str[0]==str[-1]:

return isStringPalindrome(str[1:-1])

else:

return False
#__main__

s=input("Enter the string : ")

y=isStringPalindrome(s)

if y==True:

print("String is Palindrome")

else:

print("String is Not Palindrome")

10. Write a program to count the number of vowels present in a text file.

SOURCE CODE:

fin=open("D:\\python programs\\Book.txt",'r')

str=fin.read( )

count=0

for i in str:

if i=='a' or i=='e' or i=='i' or i=='o' or i=='u':

count=count+1

print(count)

11.

Write a program to write those lines which have the character 'p' from one text file to another text file.

SOURCE CODE:

fin=open("E:\\book.txt","r")

fout=open("E:\\story.txt","a")

s=fin.readlines()

for j in s:

if 'p' in j:

fout.write(j)

fin.close()

fout.close()

12. Write a program to count number of words in a file.

SOURCE CODE:
fin=open("D:\\python programs\\Book.txt",'r')

str=fin.read( )

L=str.split()

count_words=0

for i in L:

count_words=count_words+1

print(count_words)

13.

Write a python function sin(x,n) to calculate the value of sin(x) using its taylor series expansion up to n terms.

SOURCE CODE:

import math def fact(k):

if k<=1:

return 1

else:

return k*fact(k-1)

step=int(input("How many terms : "))

x=int(input("Enter the value of x :"))

sum=0

for i in range(step+1):

sum+=(math.pow(-1,i)*math.pow(x,2*i+1))/fact(2*i+1)

print("The result of sin",'(', x, ')', "is :", sum)

14.

Write a program to generate random numbers between 1 to 6 and check whether a user won a lottery or not.

SOURCE CODE:

import random n=random.randint(1,6)

guess=int(input("Enter a number between 1 to 6 :"))

if n==guess:

print("Congratulations, You won the lottery ")

else:
print("Sorry, Try again, The lucky number was : ", n)

15. Write a program to create a library in python and import it in a program.

SOURCE CODE:

#Rect.py

class Rectangle:

def __init__(self):

print("Rectangle")

def Area(self, length, width):

self.l=length

self.w=width

print("Area of Rectangle is : ", self.l*self.w)

#Sq.py

class Square:

def __init__(self):

print("Square")

def Area(self, side):

self.a=side

print("Area of square is : ", self.a*self.a)

#Tri.py

class Triangle:

def __init__(self):

print("Trinagle")

def Area(self, base, height):

self.b=base

self.h=height

ar= (1/2)*self.b*self.h

print("Area of Triangle is : ", ar )

#main.py

from Shape import Rect

from Shape import Sq

from Shape import Tri


r=Rect.Rectangle( ) #Create an object r for Rectangle class

r.Area(10,20) # Call the module Area( ) of Rectangle class by passing argument

s=Sq.Square( ) #Create an object s for Square class

s.Area(10) # Call the module Area( ) of Square class by passing argument

t=Tri.Triangle( ) #Create an object t for Triangle class

t.Area(6,8) # Call the module Area( ) of Triangle class by passing argument

OUTPUT:

Rectangle Area of Rectangle is : 200 Square Area of square is : 100 Trinagle Area of Triangle is : 24.0

16.

Write a program to plot a bar chart in python to display the result of a school for five consecutive years.

SOURCE CODE:

import matplotlib.pyplot as pl

year=['2015','2016','2017','2018','2019'] # list of years

p=[98.50,70.25,55.20,90.5,61.50] #list of pass percentage

j=['b','g','r','m','c'] # color code of bar charts

pl.bar(year, p, width=0.2, color=j) # bar( ) function to create the bar chart

pl.xlabel("year") # label for x-axis

pl.ylabel("Pass%") # label for y-axis

pl.show( ) # function to display bar chart

17. Write a program in python to plot a graph for the function y = x2

SOURCE CODE:

import matplotlib.pyplot as pl

import numpy as np

x= np.linspace(-50,50)

y= x**2

pl.plot(x,y,linestyle='-')

pl.show( )

18.

Write a program in python to plot a pie chart on consumption of water in daily life.
SOURCE CODE:

import matplotlib.pyplot as pl

consumption=[5,30,50,3]

pl.pie(consumption, labels=['drink','bath','washing_clothes','Cooking'], autopct= ' %1.1f%% ' )

pl.show( )

19. Write a program for linear search.

SOURCE CODE:

L=eval(input("Enter the elements: "))

n=len(L)

item=eval(input("Enter the element that you want to search : "))

for i in range(n):

if L[i]==item:

print("Element found at the position :", i+1)

break

else:

print("Element not Found")

20. Write a program for bubble sort.

SOURCE CODE:

L=eval(input("Enter the elements:"))

n=len(L)

for p in range(0,n-1):

for i in range(0,n-1):

if L[i]>L[i+1]:

t=L[i]

L[i]=L[i+1]

L[i+1]=t

print("The sorted list is : ", L)

21. Write a menu based program to perform the operation on stack in python.

22. Write a menu based program to perform the operation on queue in python.

You might also like