Python 3 - Functions and OOPs Fresco
Python 3 - Functions and OOPs Fresco
1. String Methods
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'strmethod' function below.
# The function accepts following parameters:
# 1. STRING para
# 2. STRING spch1
# 3. STRING spch2
# 4. LIST li1
# 5. STRING strf
#
def stringmethod(para, special1, special2, list1, strfind):
# Write your code here
word1=para
for i in special1:
word1=word1.replace(i,'')
word2=word1[0:70]
word2=word2[-1:-71:-1]
print(word2)
l=special2.join(list(word2.replace(" ",'')))
print(l)
count=0
for i in list1:
if (i in para):count+=1
if count==len(list1):
print("Every string in ",list1,"were present")
else:print("Every string in ",list1,"were not present")
print(word1.split()[0:20])
list2=list()
freq=[]
for i in word1.split(" "):
if word1.count(i)<13:
if i in freq:pass
else:freq.append(i)
list2=freq[-1:-21:-1]
print(list2[-1:-21:-1])
print(word1.rindex(strfind))
if __name__ == '__main__':
para = input()
spch1 = input()
spch2 = input()
qw1_count = int(input().strip())
qw1 = []
for _ in range(qw1_count):
qw1_item = input()
qw1.append(qw1_item)
strf = input()
stringmethod(para, spch1, spch2, qw1, strf)
import math
import os
import random
import re
import sys
#
# Complete the 'Magic_const' function below.
#
#
#
# The function accepts INTEGER n1 as parameter.
#
def generator_Magic(n1):
# Write your code here
for i in range(3, n1+1):
gen1 = i * ((i**2) + 1) // 2
yield gen1
if __name__ == '__main__':
n = int(input().strip())
for i in generator_Magic(n):
print(int(i))
gen1 = generator_Magic(n)
print(type(gen1))
import math
import os
import random
import re
import sys
#
# Complete the 'primegenerator' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER num
# 2. INTEGER val
#
if __name__ == '__main__':
num = int(input().strip())
val = int(input().strip())
import math
import os
import random
import re
import sys
if __name__ == '__main__':
name = input()
n = int(input().strip())
cost = int(input().strip())
p1 = Movie(name,n,cost)
print(p1)
b. Problem 2
#!/bin/python3
import math
import os
import random
import re
import sys
#
#Write your code here
class comp:
def __init__(self,v1,v2):
self.real = v1
self.img = v2
def add(self,plus):
sum_r = self.real + plus.real
sum_i = self.img + plus.img
print("Sum of the two Complex numbers :{0}+{1}i".format(sum_r,sum_i))
def sub(self,minus):
sub_r = self.real - minus.real
sub_i = self.img - minus.img
if sub_i >=0:
print("Subtraction of the two Complex numbers :{0}+{1}i".format(sub_r,s
ub_i))
else:
sub_i = -sub_i
print("Subtraction of the two Complex numbers :{0}-
{1}i".format(sub_r,sub_i))
if __name__ == '__main__':
real1 = int(input().strip())
img1 = int(input().strip())
real2 = int(input().strip())
img2 = int(input().strip())
p1 = comp(real1,img1)
p2 = comp(real2,img2)
p1.add(p2)
p1.sub(p2)
import math
import os
import random
import re
import sys
class parent:
def __init__(self,total_asset):
self.total_asset = total_asset
def display(self):
print("Total Asset Worth is "+str(self.total_asset)+" Million.")
print("Share of Parents is "+str(round(self.total_asset/2,2))+" Million.")
# It is expected to create two child classes 'son' & 'daughter' for the above class
'parent'
#
#Write your code here
class parent:
def __init__(self,total_asset):
self.total_asset = total_asset
def display(self):
print("Total Asset Worth is "+str(self.total_asset)+" Million.")
print("Share of Parents is "+str(round(self.total_asset/2,2))+" Million.")
class son(parent):
def __init__(self, total, val):
parent.__init__(self, total)
self.Percentage_for_son = val
def son_display(self):
x = self.Percentage_for_son * t/100
x = round(x,2)
print("Share of Son is {} Million.".format(x))
class daughter(parent):
def __init__(self, total, val):
parent.__init__(self,total)
self.Percentage_for_daughter = val
def daughter_display(self):
y = self.Percentage_for_daughter * t/100
y = round(y,2)
print("Share of Daughter is {} Million.".format(y))
if __name__ == '__main__':
t = int(input())
sp = int(input())
dp = int(input())
obj1 = parent(t)
obj2 = son(t,sp)
obj2.son_display()
obj2.display()
obj3 = daughter(t,dp)
obj3.daughter_display()
obj3.display()
print(isinstance(obj2,parent))
print(isinstance(obj3,parent))
print(isinstance(obj3,son))
print(isinstance(obj2,daughter))
b. Problem 2
#!/bin/python3
import math
import os
import random
import re
import sys
class square:
def display(self):
print("This is a Square")
def area(self, Side):
area = round(math.pow(Side,2))
print("Area of square is ",area)
if __name__ == '__main__':
l = int(input())
b = int(input())
s = int(input())
obj1 = rectangle()
obj1.display()
obj1.area(l,b)
obj2 = square()
obj2.display()
obj2.area(s)
6. Handling Exceptions 1
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'Handle_Exc1' function below.
#
#
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.")
elif(a+b>400):
print("Their sum is out of range")
else:
print("All in range")
if __name__ == '__main__':
try:
Handle_Exc1()
except ValueError as exp:
print(exp)
7. Handling exception 2
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'FORLoop' function below.
#
def FORLoop():
# Write your code here
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
if __name__ == '__main__':
try:
d = FORLoop()
print(type(d))
print(next(d))
except StopIteration:
print('Stop Iteration : No Next Element to fetch')
8. Handling exceptions 3
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'Bank_ATM' function below.
#
# Define the Class for user-
defined exceptions "MinimumDepositError" and "MinimumBalanceError" here
class MinimumBalanceError(Exception):
pass
class MinimumDepositError(Exception):
pass
def Bank_ATM(balance,choice,amount):
b=(balance-amount)
if(balance<500):
raise ValueError("As per the Minimum Balance Policy, Balance must be at lea
st 500")
elif(balance<500 and choice ==1):
raise MinimumDepositError("As per the Minimum Balance Policy, Balance must
be at least 500")
elif(((b<500)or(amount>balance<500))and choice ==2):
raise MinimumBalanceError("You cannot withdraw this amount due to Minimum B
alance Policy")
elif(choice ==1 and amount <2000):
raise MinimumDepositError("The Minimum amount of Deposit should be 2000.")
elif(choice ==1 and amount>2000):
balance = balance + amount
print("Updated Balance Amount: ", balance)
else:
balance = balance-amount
print("Updated Balance Amount: ", balance)
if __name__ == '__main__':
bal = int(input())
ch = int(input())
amt = int(input())
try:
Bank_ATM(bal,ch,amt)
except ValueError as e:
print(e)
except MinimumDepositError as e:
print(e)
except MinimumBalanceError as e:
print(e)
9. Handling Exceptions 4
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'Library' function below.
#
def Library(memberfee,installment,book):
# Write your code here
b = ["Philosophers stone","Order of Phoenix","Chamber of Secrets","Prisoner of
Azkaban","Goblet of Fire","Half Blood Prince","Deathly Hallows 1","Deathly Hallows
2"]
c=[]
for i in b:
e=i.upper()
c.append(e)
book = book.upper()
if installment > 3:
raise ValueError("Maximum Permitted Number of Installments is 3")
elif installment == 0:
raise ZeroDivisionError("Number of Installments cannot be Zero.")
elif installment <=3:
a = memberfee/installment
print("Amount per Installment is {}".format (memberfee/installment))
if (not book in c):
raise NameError("No such book exists in this section")
else:
print("It is available in this section")
if __name__ == '__main__':
memberfee = int(input())
installment = int(input())
book = input()
try:
Library(memberfee,installment,book)
except ZeroDivisionError as e:
print(e)
except ValueError as e:
print(e)
except NameError as e:
print(e)
import math
import os
import random
import re
import sys
import datetime
#
# Complete the 'dateandtime' function below.
#
# The function accepts INTEGER val as parameter.
# The return type must be LIST.
#
def dateandtime(val,tup):
# Write your code here
list = []
if val == 1:#done
d = datetime.date(tup[0],tup[1],tup[2])
list.append(d)
dd = d.strftime('%d/%m/%Y')
list.append(dd)
if val == 2:#done
#print(int(tup[0]))
d = datetime.datetime.fromtimestamp(int(tup[0]))
d = d.date()
list.append(d)
if val == 3:
d = datetime.time(tup[0],tup[1],tup[2])
list.append(d)
#h = d.hour
h = d.strftime("%I")
list.append(h)
if val == 4:
d = datetime.date(tup[0],tup[1],tup[2])
weekday = d.strftime('%A')
list.append(weekday)
fullmonth = d.strftime('%B')
list.append(fullmonth)
day = d.strftime('%j')
list.append(day)
if val == 5:#done
d = datetime.datetime(tup[0],tup[1],tup[2],tup[3],tup[4],tup[5])
list.append(d)
return list
if __name__ == '__main__':
val = int(input().strip())
for _ in range(qw1_count):
qw1_item = int(input().strip())
qw1.append(qw1_item)
tup=tuple(qw1)
ans = dateandtime(val,tup)
print(ans)
import math
import os
import random
import re
import sys
import itertools
import operator
#
# Complete the 'usingiter' function below.
#
# The function is expected to return a TUPLE.
# The function accepts following parameters:
# 1. TUPLE tupb
#
def performIterator(tuplevalues):
# Write your code here
ListBuffer = itertools.cycle(tuplevalues[0])
SequenceRepeation = 0
SequenceStart = 0
SequenceEnd = 4
b=[]
for output in ListBuffer:
if(SequenceStart == 0):
SequenceRepeation + 1
b.append(output)
if(SequenceStart == SequenceEnd-1):
if(SequenceRepeation>= 0):
break
else:
SequenceRepeation+= 1
SequenceStart = 0
else:
SequenceStart+= 1
a=[]
a.append(tuple(b))
b=tuple(itertools.repeat(tuplevalues[1][0],len(tuplevalues[1])))
a.append(b)
c=tuple(itertools.accumulate(list(tuplevalues[2]),operator.add))
d=tuple(itertools.chain(tuplevalues[0],tuplevalues[1],tuplevalues[2],tuplevalue
s
[3]))
a.append(c)
a.append(d)
e=tuple(itertools.filterfalse(lambda x : x % 2 == 0,d))
a.append(e)
return tuple(a)
if __name__ == '__main__':
length = int(input().strip())
qw1 = []
for i in range(4):
qw2 = []
for _ in range(length):
qw2_item = int(input().strip())
qw2.append(qw2_item)
qw1.append(tuple(qw2))
tupb = tuple(qw1)
q = performIterator(tupb)
print(q)
import math
import os
import random
import re
import sys
keyval = key
textencr = str(input()).encode()
textdecr = str(input()).encode()
fptr.write(str(bk) + '\n')
fptr.close()
import math
import os
import random
import re
import sys
def usingcalendar(datetuple):
# Write your code here
year=int(datetuple[0])
mon=datetuple[1]
if year % 4== 0 or year % 100 == 0 or year % 400 == 0:
mon=2
date=calendar.TextCalendar(calendar.MONDAY)
print(date.formatmonth(year,mon))
l = []
obj = calendar.Calendar()
for day in obj.itermonthdates(year, mon):
l.append(day)
rev = l[:-8:-1]
rev.reverse()
print(rev)
count=Counter(d.strftime('%A') for d in obj.itermonthdates(year,mon) if
d.month==mon)
for i,j in count.most_common(1):
print(i)
if __name__ == '__main__':
qw1 = []
for _ in range(3):
qw1_item = int(input().strip())
qw1.append(qw1_item)
tup=tuple(qw1)
usingcalendar(tup)
14. Collections
#!/bin/python3
import math
import os
import random
import re
import sys
import collections
from collections import Counter
from collections import OrderedDict
from collections import defaultdict
#
# Complete the 'collectionfunc' function below.
#
# The function accepts following parameters:
# 1. STRING text1
# 2. DICTIONARY dictionary1
# 3. LIST key1
# 4. LIST val1
# 5. DICTIONARY deduct
# 6. LIST list1
#
if __name__ == '__main__':
from collections import Counter
text1 = input()
n1 = int(input().strip())
qw1 = []
qw2 = []
for _ in range(n1):
qw1_item = (input().strip())
qw1.append(qw1_item)
qw2_item = int(input().strip())
qw2.append(qw2_item)
testdict={}
for i in range(n1):
testdict[qw1[i]]=qw2[i]
collection1 = (testdict)
qw1 = []
n2 = int(input().strip())
for _ in range(n2):
qw1_item = (input().strip())
qw1.append(qw1_item)
key1 = qw1
qw1 = []
n3 = int(input().strip())
for _ in range(n3):
qw1_item = int(input().strip())
qw1.append(qw1_item)
val1 = qw1
n4 = int(input().strip())
qw1 = []
qw2 = []
for _ in range(n4):
qw1_item = (input().strip())
qw1.append(qw1_item)
qw2_item = int(input().strip())
qw2.append(qw2_item)
testdict={}
for i in range(n4):
testdict[qw1[i]]=qw2[i]
deduct = testdict
qw1 = []
n5 = int(input().strip())
for _ in range(n5):
qw1_item = int(input().strip())
qw1.append(qw1_item)
list1 = qw1