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

Python Funstinos and OOPS

The document contains 16 Python functions and classes that perform various tasks like string manipulation, generators, exceptions handling, date/time operations, encryption/decryption, calendar functions, and more. The functions take in parameters like strings, lists, tuples and perform operations like splitting, joining, counting, sorting, iterating, raising exceptions, and returning multiple values.

Uploaded by

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

Python Funstinos and OOPS

The document contains 16 Python functions and classes that perform various tasks like string manipulation, generators, exceptions handling, date/time operations, encryption/decryption, calendar functions, and more. The functions take in parameters like strings, lists, tuples and perform operations like splitting, joining, counting, sorting, iterating, raising exceptions, and returning multiple values.

Uploaded by

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

programs

1.)
def stringmethod(para, special1, special2, list1, strfind):
# Write your code here
word1=""
for i in para:
if(i not in special1):
word1+=i
s=word1[:70]
word2=s[-1::-1]
print(word2)
l=list(word2.split(" "))
lp=[]
for i in l:
if(i!=''):
lp.append(i)
s=''
for i in lp:
s+=i
l=list(s)
s=special2.join(l)
print(s)
c=0
for i in list1:
if( i in para):
c+=1
if(c==len(list1)):
print("Every string in "+str(list1)+" were present")
else:
print("Every string in "+str(list1)+" were not present")
l2=list(word1.split(" "))
l4=[]
for i in l2:
if(i!=''):
l4.append(i)
l2=l4
print(l2[:20])
l1=[]
for i in range(len(l2)):
l1.append(l2.count(l2[i]))
l3=[]
for i in range(len(l2)):
if(l1[i]<3 and l2[i] not in l3):
l3.append(l2[i])
print(l3[len(l3)-20:])
print(word1.rindex(strfind))

2.)
def generator_Magic(n1):
# Write your code here
l=[]
for i in range(3,n1+1):
m=i*((i**2)+1)/2
yield m
3.)
def primegenerator(num, val):
# Write your code here
l=[]
for i in range(2,num):
c=2
for j in range(2,i):
if(i%j==0):
c+=1
break
if(c==2):
l.append(i)
if(val==1):
for i in range(0,len(l),2):
yield l[i]
else:
for i in range(1,len(l),2):
yield l[i]
4.)
def Movie(name,n,cost):
s='''Movie : '''+name+'''
Number of Tickets : '''+str(n)+'''
Total Cost : '''+str(cost)
return s
5.)
class comp:
def _init_(self,real,img):
self.real=real
self.img=img
def add(self,p):
a=self.real+p.real
b=self.img+p.img
if(b>=0):
print("Sum of the two Complex numbers :"+str(a)+"+"+str(b)+"i")
else:
print("Sum of the two Complex numbers :"+str(a)+str(b)+"i")
def sub(self,p):
a=self.real-p.real
b=self.img-p.img
if(b>=0):
print("Subtraction of the two Complex numbers :"+str(a)+"+"+str(b)+"i")
else:
print("Subtraction of the two Complex numbers :"+str(a)+str(b)+"i")
6.)
class parent:
def _init_(self,t):
self.t=t
def display(self):
s=round((self.t)*50/100,2)
print("Total Asset Worth is "+str(self.t)+" Million.")
print("Share of Parents is "+str(s)+" Million.")
class son(parent):
def _init_(self,t,sp):
super()._init_(t)
self.sp=sp
def son_display(self):
s=round((self.t)*self.sp/100,2)
print("Share of Son is "+str(s)+" Million.")
class daughter(parent):
def _init_(self,t,dp):
super()._init_(t)
self.dp=dp
def daughter_display(self):
s=round((self.t)*self.dp/100,2)
print("Share of Daughter is "+str(s)+" Million.")
7.)
class rectangle:
def display(self):
print("This is a Rectangle")
def area(self,l,b):
print("Area of Rectangle is "+str(l*b))
class square:
def display(self):
print("This is a Square")
def area(self,s):
print("Area of square is "+str(s*s))
8.)
def Handle_Exc1():
# Write your code here
a=int(input())
b=int(input())
if(a>150 or b<100):
print("Input integers value out of range.")
raise ValueError
elif((a+b)>400):
print("Their sum is out of range")
raise ValueError
else:
print("All in range")
9.)
def FORLoop():
n=int(input())
l1=[]
for i in range(n):
l1.append(int(input()))
print(l1)
iter1=iter(l1)
for i in range(n):
print(next(iter1))
return iter1
10.)
class MinimumBalanceError(Exception):
def _init_(self,value):
self.value=value
def _str_(self):
return str(self.value)
class MinimumDepositError(Exception):
def _init_(self,value):
self.value=value
def _str_(self):
return str(self.value)
def Bank_ATM(balance,choice,amount):
# Write your code here
k=0
if(balance<500):
print("As per the Minimum Balance Policy, Balance must be at least 500")
k=1
raise ValueError
if(choice==1):
if(amount<2000):
k=1
raise MinimumDepositError('The Minimum amount of Deposit should be
2000.')
else:
balance=balance+amount
else:
if(balance<500):
k=1
raise MinimumBalanceError('You cannot withdraw this amount due to
Minimum Balance Policy')
else:
balance=balance-amount
if(k==0 and balance>=500):
print("Updated Balance Amount: "+str(balance))
else:
raise MinimumBalanceError('You cannot withdraw this amount due to Minimum
Balance Policy')
11.)
def Library(memberfee,installment,book):
# Write your code here
if(installment>3):
print("Maximum Permitted Number of Installments is 3")
raise ValueError
else:
if(installment==0):
print("Number of Installments cannot be Zero.")
raise ZeroDivisionError
else:
a=memberfee/installment
print("Amount per Installment is "+str(a))
h=['philosophers stone','chamber of secrets','prisoner of azkaban','goblet of
fire','order of phoenix','half blood prince','deathly hallows 1','deathly hallows
2']
if(book.lower() not in h):
print("No such book exists in this section")
raise NameError
else:
print("It is available in this section")
12.)
import datetime
def dateandtime(val,tup):
# Write your code here
date=[]
if(val==1):
date.append(datetime.date(tup[0],tup[1],tup[2]))
if(tup[1]<10):
s2="{0[2]}/0{0[1]}/{0[0]}".format(tup)
else:
s2="{0[2]}/{0[1]}/{0[0]}".format(tup)
date.append(s2)
elif(val==2):
date.append(datetime.date.fromtimestamp(tup[0]))
elif(val==3):
date.append(datetime.time(tup[0],tup[1],tup[2]))
s=tup[0]-12
s1=''
if(s<10):
s1='0'+str(s)
else:
s1=str(s)
date.append(s1)
elif(val==4):
d=datetime.date(tup[0],tup[1],tup[2])
w=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']

m=['January','February','March','April','May','June','July','August','September','O
ctober','November','December']
date.append(w[d.weekday()])
date.append(m[tup[1]-1])
d1=d.timetuple().tm_yday
d2=''
if(d1<10):
d2='00'+str(d1)
elif(d1<100):
d2='0'+str(d1)
else:
d2=str(d1)
date.append(d2)
elif(val==5):
date.append(datetime.datetime(tup[0],tup[1],tup[2],tup[3],tup[4],tup[5]))
return date
13.)
import itertools
def performIterator(tuplevalues):
# Write your code here
m=[]
l=[]
c=itertools.cycle(tuplevalues[0])
for i in range(4):
l.append(next(c))
l=tuple(l)
m.append(l)
k=tuple(itertools.repeat(tuplevalues[1][0],len(tuplevalues[1])))
m.append(k)
v=tuple(itertools.accumulate(tuplevalues[2]))
m.append(v)

y=tuple(itertools.chain(tuplevalues[0],tuplevalues[1],tuplevalues[2],tuplevalues[3]
))
m.append(y)
r=tuple(itertools.filterfalse(lambda x:x%2==0,y))
m.append(r)
return tuple(m)
14.)
from cryptography.fernet import Fernet
def encrdecr(keyval, textencr, textdecr):
# Write your code here
m=[]
k=Fernet(keyval)
m.append(k.encrypt(textencr))
s=k.decrypt(textdecr)
m.append(s.decode())
return m
15.)
import calendar
from collections import Counter
def usingcalendar(datetuple):
# Write your code here
m=datetuple[1]
if(calendar.isleap(datetuple[0])):
m=2
print(calendar.month(datetuple[0],m))
c=calendar.Calendar()
l=[]
w=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
for i in c.itermonthdates(datetuple[0],m):
l.append(i)
print(l[len(l)-7:])
year = datetuple[0]
month = m
count = Counter(d.strftime('%A') for d in c.itermonthdates(year, month) if
d.month==month)
for i in count:
print(i)
break
else:
m=datetuple[1]
print(calendar.month(datetuple[0],m))
c=calendar.Calendar()
l=[]
w=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
for i in c.itermonthdates(datetuple[0],m):
l.append(i)
print(l[len(l)-7:])
year = datetuple[0]
month = m
count = Counter(d.strftime('%A') for d in c.itermonthdates(year, month) if
d.month==month)
for i in count:
print(i)
break
16.)
from collections import Counter
from collections import OrderedDict
def collectionfunc(text1, dictionary1, key1, val1, deduct, list1):
# Write your code here
l=text1.split(" ")
v=[]
for i in l:
v.append(l.count(i))
d={}
for i in range(len(l)):
if(l[i] not in d):
d[l[i]]=v[i]
k=dict(sorted(d.items(), key =
lambda kv:(kv[0], kv[1])))
print(k)
b=Counter(dictionary1)
for i in deduct:
b[i]=b[i]-deduct[i]
d=dict(b)
print(d)
od=OrderedDict()
for i in range(len(key1)):
od[key1[i]]=val1[i]
od.pop(key1[1])
od[key1[1]]=val1[1]
print(dict(od))
num={}
even=[]
odd=[]
for i in list1:
if(i%2==0):
even.append(i)
else:
odd.append(i)
if(len(odd)>0):
num['odd']=odd
if(len(even)>0):
num['even']=even
print(num)

You might also like