Python 3 Functions and OOPs FP
Python 3 Functions and OOPs FP
#
# 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
#
rword2=word1[69::-1]
print(rword2)
number=word1
splitAll = number.split()
print(splitAll[0:20])
mylist=[]
myDict = dict()
for t in splitAll:
myDict[t]=myDict.get(t,0)+1
for x,y in myDict.items():
if(y<3):
mylist.append(x)
print(mylist[-20:])
print(word1.rfind(strfind))
1 magic constant
#
# Complete the 'Magic_const' function below.
#
#
#
# The function accepts INTEGER n1 as parameter.
#
def generator_Magic(n1):
for i in range(3, n1+1):
gen1 = i * ((i**2) + 1) // 2
yield gen1
#
# Complete the 'primegenerator' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER num
# 2. INTEGER val
#
def __str__(self):
#return self.movieName
#return self.numberTickets
#return self.totalCost
return "Movie : {}\nNumber of Tickets : {}\nTotal Cost :
{}".format(self.movieName,self.numberTickets,self.totalCost)
task 2
Define the class 'comp' that represents the Real and Imaginary
Polymorphism
class rectangle:
def display(self):
print("This is a Rectangle")
class square:
def display(self):
print("This is a Square")
1. Handling Exceptions - 1
Exception handling 1.
def Handle_Exc1():
a=int(input())
b=int(input())
c=a+b
if a>150 or b<100:
raise ValueError("Input integers value out of range.")
elif c>400:
raise ValueError("Their sum is out of range")
else:
print("All in range")
1. Handling Exceptions - 2
Write the function definition for the function 'FORLoop'
def FORLoop():
n = int(input())
l1 = [0]*n
for i in range(len(l1)):
l1[i]=int(input())
print(l1[0:n])
iter1 = iter(l1)
for i in range(len(l1)):
print(next(iter1))
return iter1
Handling Exceptions 3
Bank_ATM
def Bank_ATM(balance,choice,amount):
#print(balance)
#print(choice)
#print(amount)
if balance < 500:
raise(ValueError("As per the Minimum Balance Policy, Balance must be at
least 500"))
if choice == 1:
if amount < 2000:
raise(MinimumDepositError("The Minimum amount of Deposit should be
2000."))
else:
balance+=amount
print("Updated Balance Amount: ",balance)
if choice == 2:
if balance-amount < 500:
raise(MinimumBalanceError("You cannot withdraw this amount due to
Minimum Balance Policy"))
else:
balance-=amount
print("Updated Balance Amount: ",balance)
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
self.total = total
def son_display(self):
x = self.total * (self.Percentage_for_son / 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
self.total = total
def daughter_display(self):
x = self.total * (self.Percentage_for_daughter / 100)
x = round(x,2)
print("Share of Daughter is {} Million.".format(x))
1. Handling Exceptions 4
def Library(memberfee,installment,book):
# Write your code here
#print(memberfee)
#print(installment)
#print(book)
if installment > 3:
raise(ValueError("Maximum Permitted Number of Installments is 3"))
if installment == 0:
raise(ZeroDivisionError("Number of Installments cannot be Zero."))
else:
print ("Amount per Installment is ", memberfee / installment)
if book == 'Philosophers stone' or book == 'Chamber of Secrets' or book ==
'prisoner of azkaban' or book == 'Goblet of Fire' or book == 'order of phoenix' or
book == 'Half Blood Prince' or book == 'Deathly Hallows 1' or book == 'deathly
hallows 2':
print ("It is available in this section")
else:
raise(NameError("No such book exists in this section"))
Python DateTime
list = []
if val == 1:
d = datetime.date(tup[0],tup[1],tup[2])
list.append(d)
dd = d.strftime('%d/%m/%Y')
list.append(dd)
if val == 2:
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.strftime("%I")
list.append(h)
if val == 4:
d = datetime.date(tup[0],tup[1],tup[2])
#list.append(d)
weekday = d.strftime('%A')
list.append(weekday)
fullmonth = d.strftime('%B')
list.append(fullmonth)
day = d.strftime('%j')
list.append(day)
if val == 5:
d = datetime.datetime(tup[0],tup[1],tup[2],tup[3],tup[4],tup[5])
list.append(d)
return list
Python - Itertools (NOT YET COMPLETED)
#
# Complete the 'usingiter' function below.
#
# The function is expected to return a TUPLE.
# The function accepts following parameters:
# 1. TUPLE tupb
#
import itertools
import operator
from itertools import chain
def performIterator(tuplevalues):
# Write your code here
mainlist = list()
list1 = list()
mainlist.append(list1[0:4])
list2 = list()
tupcount = len(tuplevalues[1])
rep = list(itertools.repeat(num,tupcount))
mainlist.append(rep)
tup3 = tuplevalues[2]
result = itertools.accumulate(tup3,operator.add)
list3 = list()
mainlist.append(list3)
length = len(tuplevalues)
list4 = list()
for i in range(length):
for var in range(len(tuplevalues[i])):
list4.append(tuplevalues[i][var])
mainlist.append(list4)
#
# Complete the 'encrdecr' function below.
#
# The function is expected to return a LIST.
# The function accepts following parameters:
# 1. STRING keyval
# 2. STRING textencr
# 3. Byte-code textdecr
#
from cryptography.fernet import Fernet
Python - Calendar
#
# Complete the 'calen' function below.
#
# The function accepts TUPLE datetuple as parameter.
#
import calendar
import datetime
from collections import Counter
def usingcalendar(datetuple):
import collections
items = collections.Counter(li)
y = sorted(items.items())
fix = str(y).replace('[(', '{').replace(')]',
'}').replace('\',','\':').replace('), (',', ')
print(fix)
items = collections.Counter(dictionary1)
even=list()
odd=list()
for i in list1:
if (i % 2) == 0:
even.append(i)
else:
odd.append(i)
oedict = {}