0% found this document useful (0 votes)
18 views13 pages

Programs-Set 1

Uploaded by

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

Programs-Set 1

Uploaded by

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

GRADE:XII

Computer Science- Python Programs


1.Write a program to find sum of elements of List recursively
def findSum(lst,num):
if num==0:
return 0
else:
return lst[num-1]+findSum(lst,num-1)
mylist = [] # Empty List
#Loop to input in list
num = int(input("Enter how many number :"))
for i in range(num):
n = int(input("Enter Element "+str(i+1)+":"))
mylist.append(n) #Adding number to list
sum = findSum(mylist,len(mylist))
print("Sum of List items ",mylist, " is :",sum)
2. Write a Program to search any word in given string/sentence
def countWord(str1,word):
s = str1.split()
count=0
for w in s:
if w==word:
count+=1
return count
str1 = input("Enter any sentence :")
word = input("Enter word to search in sentence :")
count = countWord(str1,word)
if count==0:
print("## Sorry! ",word," not present ")
else:
print("## ",word," occurs ",count," times ## ")
3. Write a Program to read and display file content line by line with each word
separated by „#‟

1
f = open("file1.txt")
for line in f:
words = line.split()
for w in words:
print(w+'#',end='')
print()
f.close()
4. Program to read the content of file and display the total number of
consonants, uppercase, vowels and lower case characters‟
f = open("file1.txt")
v=0
c=0
u=0
l=0
o=0
data = f.read()
vowels=['a','e','i','o','u']
for ch in data:
if ch.isalpha():
if ch.lower() in vowels:
v+=1
else:
c+=1
if ch.isupper():
u+=1
elif ch.islower():
l+=1
elif ch!=' ' and ch!='\n':
o+=1
print("Total Vowels in file :",v)
print("Total Consonants in file n :",c)
print("Total Capital letters in file :",u)
print("Total Small letters in file :",l)
print("Total Other than letters :",o)
f.close()
5. Write a menu driven program in Python using user defined function to
i) Check if a string is a palindrome
ii) Find length of a string
iii) Reverse a string

def palindrome(s):
for i in range(0, int(len(s)/2)):
if s[i]!=s[len(s)-i-1]:
print(“The string is not a palindrome”)
break
else:
2
print(“The string is a palindrome”)
def lens(s):
count=0
for i in s:
count=count+1
print(“The length of the string is”,count)
def revs(s):
print(“The reverse of the string is”)
for i in range(0,len(s)):
a=s[len(s)-i-1]
print(a,end=””)
while(1):
print(“”\nmenu
1. Palindrome
2. Length of string
3. Reverse a string
4. Exit””)
ch=int(input(“Enter choice”))
if(ch==1):
s=input(“Enter the string”)
palindrome(s)
elif(ch==2):
s=input(“Enter the string”)
lens(s)
elif(ch==3):
s=input(“Enter the string”)
revs(s)
elif(ch==4):
break
else:
print(“invalid input”)

6.Write a program in Python using user defined function to


i) Selection sort
ii) Bubble sort

def selection():
list=[]
n=int(input(“Enter a value for n”))
for i in range(n):
l=int(input(“Enter a value for list:”))
list.append(l)
print(list)
for i in range(0,len(list)):
for j in range(i+1,len(list)-1):
if list[i]>list[j]:
temp=list[i]
list[i]=list[j]
list[j]=temp
print(“The numbers after sorting”)

3
print(list)
def bubble():
list=[]
n=int(input(“Enter a valu for n”))
for i in range(n):
l=int(input(“Enter a value for list:”))
list.append(l)
print(list)
for i in range(0,len(list)):
for j in range(0,len(list)-i-1):
if list[j]>list[j+1]:
temp=list[j]
list[j]=list[j+1]
list[j+1]=temp
print(“The numbers after sorting”)
print(list)
while(1):
print(“menu
1. Selection Sort
2. Bubble Sort
3. Exit”)
ch=int(input(“Enter choice:”))
if(ch==1):
selection()
elif ch==2:
bubble()
else:
break
7. Write a Program to implement Stack in Python using List
def isEmpty(S):
if len(S)==0:
return True
else:
return False
def Push(S,item):
S.append(item)
top=len(S)-1
def Pop(S):
if isEmpty(S):
return "Underflow"
else:
val = S.pop()
if len(S)==0:
top=None
else:
top=len(S)-1
return val
def Peek(S):
if isEmpty(S):
return "Underflow"

4
else:
top=len(S)-1
return S[top]
def Show(S):
if isEmpty(S):
print("Sorry No items in Stack ")
else:
t = len(S)-1
print("(Top)",end=' ')
while(t>=0):
print(S[t],"<==",end=' ')
t-=1
print()
# main begins here
S=[] #Stack
top=None
while True:
print("**** STACK DEM ONSTRATION ******")
print("1. PUSH ")
print("2. POP")
print("3. PEEK")
print("4. SHOW STACK ")
print("0. EXIT")
ch = int(input("Enter your choice :"))
if ch==1:
val = int(input("Enter Item to Push :"))
Push(S,val)
elif ch==2:
val = Pop(S)
if val=="Underflow":
print("Stack is Empty")
else:
print("\nDeleted Item was :",val)
elif ch==3:
val = Peek(S)
if val=="Underflow":
print("Stack Empty")
else:
print("Top Item :",val)
elif ch==4:
Show(S)
elif ch==0:
print("Bye")
break
8. Write a Program to implement Queue in Python using List
def isEmpty(Q):
if len(Q)==0:
return True
else:
return False

5
def Enqueue(Q,item):
Q.append(item)
if len(Q)==1:
front=rear=0
else:
rear=len(Q)-1
def Dequeue(Q):
if isEmpty(Q):
return "Underflow"
else:
val = Q.pop(0)
if len(Q)==0:
front=rear=None
return val
def Peek(Q):
if isEmpty(Q):
return "Underflow"
else:
front=0
return Q[front]
def Show(Q):
if isEmpty(Q):
print("Sorry No items in Queue ")
else:
t = len(Q)-1
print("(Front)",end=' ')
front = 0
i=front
rear = len(Q)-1
while(i<=rear):
print(Q[i],"==>",end=' ')
i+=1
print()
Q=[] #Queue
front=rear=None
while True:
print("**** QUEUE DEMONSTRATION ******")
print("1. ENQUEUE ")
print("2. DEQUEUE")
print("3. PEEK")
print("4. SHOW QUEUE ")
print("0. EXIT")
ch = int(input("Enter your choice :"))
if ch==1:
val = int(input("Enter Item to Insert :"))
Enqueue(Q,val)
elif ch==2:
val = Dequeue(Q)
if val=="Underflow":
print("Queue is Empty")

6
else:
print("\nDeleted Item was :",val)
elif ch==3:
val = Peek(Q)
if val=="Underflow":
print("Queue Empty")
else:
print("Front Item :",val)
elif ch==4:
Show(Q)
elif ch==0:
print("Bye")
break
9. Write a program with a user-defined function with string as a parameter which
replaces all vowels in the string with ‘*’.

def strep(str):
# convert string into list
str_lst =list(str)
# Iterate list
for i in range(len(str_lst)):
# Each Character Check with Vowels
if str_lst[i] in 'aeiouAEIOU':
# Replace ith position vowel with'*'
str_lst[i]='*'
#to join the characters into a new string.
new_str = "".join(str_lst)
return new_str
def main():
line = input("Enter string: ")
print("Orginal String")
print(line)
print("After replacing Vowels with '*'")
print(strep(line))
main()

10. Write a recursive code to find the sum of all elements of a list.

7
def lstSum(lst,n):
if n==0:
return 0
else:
return lst[n-1]+lstSum(lst,n-1)
mylst = [] # Empty List
#Loop to input in list
num = int(input("Enter how many number :"))
for i in range(num):
n = int(input("Enter Element "+str(i+1)+":"))
mylst.append(n) #Adding number to list
sum = lstSum(myl
st,len(mylst))
print("Sum of List items ",mylst, " is :",sum)

11. Write a Python code to find the size of the file in bytes, the number of lines,
number of words and no. of character.

import os
lines = 0
words = 0
letters = 0
filesize = 0
for line in open("Mydoc.txt"):
lines += 1
letters += len(line)
# get the size of file
filesize = os.path.getsize("Mydoc.txt")

# A flag that signals the location outside the word.


pos = 'out'
for letter in line:
if letter != ' ' and pos == 'out':
words += 1

8
pos = 'in'
elif letter == ' ':
pos = 'out'
print("Size of File is",filesize,'bytes')
print("Lines:", lines)
print("Words:", words)
print("Letters:", letters)

12. Write a program to search the record of a particular student from CSV file on
the basis of inputted name.

import csv
#input Roll number you want to search
number = input('Enter number to find: ')
found=0
#read csv, and split on "," the line
with open('Student_Details.csv') as f:
csv_file = csv.reader(f, delimiter=",")
#loop through csv list
for row in csv_file:
#if current rows index value (here 0) is equal to input, print that row
if number ==row[0]:
print (row)
found=1
else:
found=0
if found==1:
pass
else:
print("Record Not found")

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

#Let's create a package named Mypackage, using the following steps:


#• Create a new folder named NewApp in D drive (D:\NewApp)
#• Inside NewApp, create a subfolder with the name 'Mypackage'.
#• Create an empty __init__.py file in the Mypackage folder
#• Create modules Area.py and Calculator.py in Mypackage folder with following code

# Area.py Module
import math
def rectangle(s1,s2):
area = s1*s2
return area
def circle(r):
area= math.pi*r*r
return area
def square(s1):
area = s1*s1
return area
def triangle(s1,s2):
area=0.5*s1*s2
return area

# Calculator.py Module
def sum(n1,n2):
s = n1 + n2
return s
def sub(n1,n2):
r = n1 - n2
return r
def mult(n1,n2):
m = n1*n1
return m

10
def div(n1,n2):
d=n1/n2
return d

# main() function
from Mypackage import Area
from Mypackage import Calculator
def main():
r = float(input("Enter Radius: "))
area =Area.circle(r)
print("The Area of Circle is:",area)
s1 = float(input("Enter side1 of rectangle: "))
s2 = float(input("Enter side2 of rectangle: "))
area = Area.rectangle(s1,s2)
print("The Area of Rectangle is:",area)
s1 = float(input("Enter side1 of triangle: "))
s2 = float(input("Enter side2 of triangle: "))
area = Area.triangle(s1,s2)
print("The Area of TriRectangle is:",area)
s = float(input("Enter side of square: "))
area =Area.square(s)
print("The Area of square is:",area)
num1 = float(input("\nEnter First number :"))
num2 = float(input("\nEnter second number :"))
print("\nThe Sum is : ",Calculator.sum(num1,num2))
print("\nThe Multiplication is : ",Calculator.mult(num1,num2))
print("\nThe sub is : ",Calculator.sub(num1,num2))
print("\nThe Division is : ",Calculator.div(num1,num2))
main()
14. Write a python program to implement searching methods based on user
choice using a list data-structure. (linear & binary)

#Linear Search Function Definition


def Linear_Search( lst, srchItem):

11
found= False
for i in range(len(lst)):
if lst[i] == srchItem:
found = True
print(srchItem, ' was found in the list at index ', i)
break
if found == False:
print(srchItem, ' was not found in the list!')
#Binary Search Definition
def binary_Search(Lst,num):
start = 0
end = len(Lst) - 1
mid = (start + end) // 2
# We took found as False that is, initially
# we are considering that the given number
# is not present in the list unless proven
found = False
position = -1
while start <= end:
if Lst[mid] == num:
found = True
position = mid
print('Number %d found at position %d'%(num, position+1))
break
if num > Lst[mid]:
start = mid + 1
mid = (start + end) // 2
else:
end = mid - 1
mid = (start + end) // 2
if found==False:
print('Number %d not found' %num)

# DRIVER CODE
12
def main():
print ("SEARCH MENU")
print ("1. LINEAR SERACH")
print ("2. BINARY SEARCH")
print ("3. EXIT")
choice=int(input("Enter your Choice [ 1 - 3 ]: "))
arr = [12, 34, 54, 2, 3]
n = len(arr)
if choice==1:
print("The List contains : ",arr)
num=int(input("Enter number to be searched: "))
index = Linear_Search(arr,num)
if choice==2:
arr = [2, 3,12,34,54] #Sorted Array
print("The List contains : ",arr)
num=int(input("Enter number to be searched: "))
result = binary_Search(arr,num)
main()
15. Write a program to remove all the lines that contain the character `a' in a
file and write it to another file
f1 = open("Mydoc.txt")
f2 = open("copyMydoc.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print('## File Copied Successfully! ##')
f1.close()
f2.close()
f2 = open("copyMydoc.txt","r")
print(f2.read())

13

You might also like