Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Prac12 2324

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

#PGM-1

#Program for factorial of a number using Recursion

def factorial(n):

if n==1:

return n

else:

return n*factorial(n-1) #Recusive code

num=int(input("Enter Number"))

if num<0:

print("Sorry, Factorial does not exist for nrgstive numbers.")

elif num==0:

print("Factorial of 0 is 1")

else:

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

output;

Enter Number4

Factorial of 4 is 24
Prog 2;

# program to compute sum of the numbers in list using recursion

def findSum(list2):

if len(list2)==1:

return list2[0]

else:

return list2[0]+findSum(list2[1:])

list1 =[]

list1 = [1,2,3,4,5]

print("sum of the elements of the list is:",findSum(list1))

findSum(list1)

output;

sum of the elements of the list is: 15


# pgm 3

#Program for fibbonicci series using Recursion

def fibonacci(n):

if n==1:

return 0 #1st term of a fibonacci series is 0

elif n==2:

return 1 #2nd term of fibonacci series is 1

else:

return(fibonacci(n-1)+fibonacci(n-2)) #Recursive code

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

#check whether the number of terms is valid

if num<=0:

print("Please enter a positive integer")

else:

print("Fibonacci sequence:")

for x in range(1,num+1):

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

print(".........")

output;

How many terms you wnat to display:5

Fibonacci sequence:

0 1 1 2 3 .........

>>>
Pgm4:

# Python code to

# demonstrate readlines()

L = ["India is My country\n", " All indians are my brothers and sisiters\n", "we love sainik school\n"]

# writing to file

file1 = open('myfile.txt', 'w')

file1.writelines(L)

file1.close()

# Using readlines()

file1 = open('myfile.txt', 'r')

Lines = file1.readlines()

count = 0

# Strips the newline character

for line in Lines:

print("Line{}: {}".format(count, line.strip()))

output:

Line0: India is My country

Line0: All indians are my brothers and sisiters

Line0: we love sainik school

>>>
Pgm5:

#Main=open("Eemail.txt")

Main=open("new.txt")

Readlt=Main.read()

NVowels=0

NConsonants=0

NUpperCase=0

NLowerCase=0

for C in Readlt:

if C.isupper():

NUpperCase=NUpperCase+1

if C.islower():

NLowerCase= NLowerCase+1

if(C=='a' or C=='e' or C=='i' or C=='A' or C=='u' or C=='E' or C=='l' or C=='O' or C=='U'):

NVowels=NVowels+1

if(C!='a' or C!='e' or C!='i' or C!='A' or C!='u' or C!='E' or C!='l' or C!='O' or C!='U'):

NConsonants=NConsonants+1

print("The Number of Vowels in the File is",NVowels)

print("The Number of Consonants in the File is",NConsonants)

print("The Number of Upper Case Character in the File is",NUpperCase)

print("The Number of Lower Case Character in the File is",NLowerCase)

output:

The Number of Vowels in the File is 27

The Number of Consonants in the File is 100

The Number of Upper Case Character in the File is 15

The Number of Lower Case Character in the File is 65

>>>
Pgm6:

import pickle

# take user input to take the amount of data

number_of_data = int(input('Enter the number of data : '))

data = []

# take input of the data

for i in range(number_of_data):

raw = input('Enter data '+str(i)+' : ')

data.append(raw)

# open a file, where you ant to store the data

file = open('important1.txt', 'wb')

# dump information to that file

pickle.dump(data, file)

# close the file

file.close()

# open a file, where you stored the pickled data

file = open('important1.txt', 'rb')

# dump information to that file

data = pickle.load(file)
# close the file

file.close()

print('Showing the pickled data:')

cnt = 0

for item in data:

print('The data ', cnt, ' is : ', item)

cnt += 1

output;

Enter the number of data : 5

Enter data 0 : 5

Enter data 1 : 4

Enter data 2 : 6

Enter data 3 : 9

Enter data 4 : 8

Showing the pickled data:

The data 0 is : 5

The data 1 is : 4

The data 2 is : 6

The data 3 is : 9

The data 4 is : 8

>>>
Prog 7:

#AIM : PYTHON PROGRAM FOR STACK IMPLEMENTATION#

############ STACK IMPLEMENTATION ###########

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

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

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 !!")

output:

STACK OPERATIONS

1.Push

2.Pop

3.Peek

4.Display

5.Exit

Enter your choice (1-5):4

Stack Empty
Pgm8:

myfile = open("WithoutA.txt" )

myfile2 = open ("witha.txt","w")

Str=" "

Str2=" "

Main=myfile.read()

SplitLineMain = (Main.splitlines())

for x in SplitLineMain:

if " a" in x:

Str = Str+ x + " \n"

else:

Str2 = Str2 + x + "\n"

myfile.close()

wmyfile=open("WithoutA.txt","w")

myfile2.write(Str)

myfile2.write("\n")

myfile2.close()

wmyfile.write(Str2)

wmyfile.write("\n")

wmyfile.close()

print("the text file has been classified successfully...")

output:

the text file has been classified successfully...

>>>
Pgm9:

# import random

import random

num = random.random()

print("any random number generated is ",num)

s=int(input("start value"))

e=int(input("end value"))

print( "random number between start and end id ",random.randint(s, e))

# prints a random value from the list

list1 = [1, 2, 3, 4, 5, 6]

print(random.choice(list1))

# prints a random item from the string

string = "Ajinkyan"

print(random.choice(string))

output:

any random number generated is 0.9121134877069548

start value455

end value622

random number between start and end id 471

A
Pgm10: (1)

# program to check prime numbers

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

# If given number is greater than 1

if num >= 1:

# Iterate from 2 to n / 2

for i in range(2, int(num/2)+1):

# If num is divisible by any number between

# 2 and n / 2, it is not prime

if (num % i) == 0:

print(num, "is not a prime number")

break

else:

print(num, "is a prime number")

else:

print(num, "is not a prime number")

output:

Enter a number:45

45 is not a prime number


Pgm 10: (2)

def isEmpty(stk):#checks whether the stack is empty or not

if stk==[]:

return True

else:

return False

def Push(stk,item):#Alllow addition to the stack

stk.append(item)

top=len(stk)-1

def Pop(stk):

if isEmpty(stk):#verifies whether the stack is empty or not

print("Underflow")

else:#Allow deletions from the stack

item=stk.pop()

if len(stk)==0:

top=None

else:

top=len(stk)

print("Popped item is"+str(item))

def Disply(stk):

if isEmpty(stk):

print("stack is empty")

else:

top=len(stk)-1

print("Elements in the stack are:")

for i in range(top,-1,-1):
print(str(stk[i]))

#executable code

#if _name_=="_main_":

stk=[]

top=None

Push(stk,1)

Disply(stk)

Push(stk,2)

Disply(stk)

Disply(stk)

Push(stk,3)

Disply(stk)

Push(stk,4)

Disply(stk)

Push(stk,100)

Disply(stk)

Push(stk,-77)

Disply(stk)

Pop(stk)

Pop(stk)

Pop(stk)

Disply(stk)

Output:

Elements in the stack are:

Elements in the stack are:


2

Elements in the stack are:

Elements in the stack are:

Elements in the stack are:

Elements in the stack are:

100

Elements in the stack are:

-77

100

1
Popped item is-77

Popped item is100

Popped item is4

Elements in the stack are:

1
Pgm 11:

# Pgm-12> CALCULATE THE COMPOUND INTEREST FOR A PRINCIPAL AMOUNT ON A R

p=float(input("Enter the Principal Amount of your Loan:"))

r=float(input("Enter the Rate of interest you want:")) #All inputs are Accepted

t=float(input("Enter the Time in Years:"))

x=(1+r/100)**t #Compound Interest is Calculated

Cl=p*x-p

print("Compound Interest fot the Principal Amount",p,"is",round(Cl,2))

output:

Enter the Principal Amount of your Loan:100000

Enter the Rate of interest you want:5

Enter the Time in Years:5

Compound Interest fot the Principal Amount 100000.0 is 27628.16

>>>
Pgm 12:

# program to check string is palindrome or not

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(s,"is string is Palindrome")

else:

print(s,"string is not palindrome")

output:

Enter the string:hello

hello string is not palindrome


Pgm13:

# to count number of words in a file

fin=open("new.txt",'r')

str=fin.read()

L=str.split()

count_words=0

for i in L:

count_words=count_words+1

print("There are",count_words,"words in the file.")

output:

There are 19 words in the file.

>>>
Pgm14:

"""Infix to postfix conversion

"""

class Stack:

def __init__(self):

self.items = []

self.length = 0

def push(self, val):

self.items.append(val)

self.length += 1

def pop(self):

if self.empty():

return None

self.length -= 1

return self.items.pop()

def size(self):

return self.length

def peek(self):

if self.empty():

return None
return self.items[0]

def empty(self):

return self.length == 0

def __str__(self):

return str(self.items)

precedence = {}

precedence['*'] = 3

precedence['/'] = 3

precedence['+'] = 2

precedence['-'] = 2

precedence['('] = 1

def convert(expression):

print(__convert(expression.split()))

def __convert(tokens):

postfix = []

opstack = Stack()

for token in tokens:

if token.isidentifier():

postfix.append(token)

elif token == '(':

opstack.push(token)
elif token == ')':

while True:

temp = opstack.pop()

if temp is None or temp == '(':

break

elif not temp.isidentifier():

postfix.append(temp)

else: # must be operator

if not opstack.empty():

temp = opstack.peek()

while not opstack.empty() and precedence[temp] >= precedence[token] and


token.isidentifier():

postfix.append(opstack.pop())

temp = opstack.peek()

opstack.push(token)

while not opstack.empty():

postfix.append(opstack.pop())

return postfix

print("POSTFIX OF = A+B IS")

convert("A + B")

print("POSTFIX OF = A + B * C IS")
convert("A + B * C")

print("POSTFIX OF = A * ( B + C ) + D IS")

convert("A * ( B + C ) + D")

output:

POSTFIX OF = A+B IS

['A', 'B', '+']

POSTFIX OF = A + B * C IS

['A', 'B', 'C', '*', '+']

POSTFIX OF = A * ( B + C ) + D IS

['A', 'B', 'C', '+', 'D', '+', '*']

>>>
Pgm15:

# Python program to evaluate value of a postfix expression

# Class to convert the expression

class Evaluate:

# Constructor to initialize the class variables

def __init__(self, capacity):

self.top = -1

self.capacity = capacity

# This array is used a stack

self.array = []

# check if the stack is empty

def isEmpty(self):

return True if self.top == -1 else False

# Return the value of the top of the stack

def peek(self):

return self.array[-1]

# Pop the element from the stack

def pop(self):

if not self.isEmpty():

self.top -= 1

return self.array.pop()

else:
return "$"

# Push the element to the stack

def push(self, op):

self.top += 1

self.array.append(op)

# The main function that converts given infix expression

# to postfix expression

def evaluatePostfix(self, exp):

# Iterate over the expression for conversion

for i in exp:

# If the scanned character is an operand

# (number here) push it to the stack

if i.isdigit():

self.push(i)

# If the scanned character is an operator,

# pop two elements from stack and apply it.

else:

val1 = self.pop()

val2 = self.pop()

self.push(str(eval(val2 + i + val1)))
return int(self.pop())

# Driver program to test above function

#exp = "231*+9-"

exp="17+"

obj = Evaluate(len(exp))

print( "postfix evaluation: %d"%(obj.evaluatePostfix(exp)))

output:

postfix evaluation: 8

>>>
Pgm16:

import csv

fh=open("student199.csv",'w')

stuwriter=csv.writer(fh)

stuwriter.writerow(['Rollno','Name','Marks'])

for i in range(2):

print("stu rec",(i+1))

rollno=int(input("tell roll no"))

name=input("tell name")

marks=float(input(" tell marks"))

sturec=[rollno,name,marks]

stuwriter.writerow(sturec)

fh.close()

output:

stu rec 1

tell roll no6416

tell nametejas

tell marks98

stu rec 2

tell roll no6410

tell nameguru

tell marks98

>>>

You might also like