Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
111 views

Python 3 Functions and OOPs FP

The document discusses Python functions and OOP concepts including: 1. A function to perform string methods on a given paragraph. 2. A generator function that yields magic numbers based on an input. 3. A function to generate prime numbers based on inputs. 4. Classes to represent movies and complex numbers, demonstrating object-oriented concepts. 5. Exception handling functions and user-defined exceptions. 6. Inheritance between classes.

Uploaded by

jitaha
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)
111 views

Python 3 Functions and OOPs FP

The document discusses Python functions and OOP concepts including: 1. A function to perform string methods on a given paragraph. 2. A generator function that yields magic numbers based on an input. 3. A function to generate prime numbers based on inputs. 4. Classes to represent movies and complex numbers, demonstrating object-oriented concepts. 5. Exception handling functions and user-defined exceptions. 6. Inheritance between classes.

Uploaded by

jitaha
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/ 9

Python 3 - Functions and OOPs_FP

1. hands on python string methods

#
# 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):


for myChar in special1:
para = para.replace(myChar,"")
word1=para

m
er as
rword2=word1[69::-1]

co
print(rword2)

eH w
myspaceremove=rword2.replace(" ", "")

o.
myspaceremove=myspaceremove.replace("
rs e ", "")
myword= special2.join(myspaceremove)
ou urc
print(myword)

if all(SearchStr in para for SearchStr in list1):


print("Every string in %s were present" %list1)
o

else:
aC s

print("Every string in %s were not present" %list1)


v i y re

number=word1
splitAll = number.split()
print(splitAll[0:20])
ed d

mylist=[]
ar stu

myDict = dict()
for t in splitAll:
myDict[t]=myDict.get(t,0)+1
for x,y in myDict.items():
if(y<3):
sh is

mylist.append(x)
print(mylist[-20:])
Th

print(word1.rfind(strfind))

1 magic constant

#
# Complete the 'Magic_const' function below.
#
#
#
# The function accepts INTEGER n1 as parameter.
#

def generator_Magic(n1):

This study source was downloaded by 100000830658032 from CourseHero.com on 08-24-2021 03:48:19 GMT -05:00

https://www.coursehero.com/file/72192067/Python-3-Functions-and-OOPs-FPtxt/
for i in range(3, n1+1):
gen1 = i * ((i**2) + 1) // 2
yield gen1

Python 3 Functions and OOPs - Prime Number Generator

#
# 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 primegenerator(num, val):


# Write your code here
x = 0
for i in range(2,num):
if(len([j for j in range(2,i-1) if i%j==0]) == 0):
x = x + 1

m
if(int(val) == 0):

er as
if (x % 2) == 0:

co
yield i

eH w
if(int(val) == 1):
if (x % 2) != 0:

o.
yield i rs e
ou urc
Python 3 - Functions and OOPs - Classes and Objects 1

Define a class 'Movie' that represents


o

# Write your code here


aC s

class Movie:
v i y re

def __init__(self, val1, val2, val3):


self.movieName= val1
self.numberTickets = val2
self.totalCost = val3
ed d

def __str__(self):
ar stu

#return self.movieName
#return self.numberTickets
#return self.totalCost
return "Movie : {}\nNumber of Tickets : {}\nTotal Cost :
{}".format(self.movieName,self.numberTickets,self.totalCost)
sh is

task 2
Th

Define the class 'comp' that represents the Real and Imaginary

#Write your code here


class comp(object):
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary

def add(self, other):


sum = complex(self.real + other.real, self.imaginary + other.imaginary)
sum = str(sum).replace('j','i').replace('(','').replace(')','')
print ("Sum of the two Complex numbers :" +sum)

def sub(self, other):


diff = complex(self.real - other.real, self.imaginary - other.imaginary)

This study source was downloaded by 100000830658032 from CourseHero.com on 08-24-2021 03:48:19 GMT -05:00

https://www.coursehero.com/file/72192067/Python-3-Functions-and-OOPs-FPtxt/
diff = str(diff).replace('j','i').replace('(','').replace(')','')
if diff == "0i":
diff = "0+0i"
print ("Subtraction of the two Complex numbers :" +diff)

Addition and Subtraction of Complex Numbers

2. Classes and Objects

Polymorphism
class rectangle:
def display(self):
print("This is a Rectangle")

def area(self, Length, Breadth):


area = Length * Breadth
print("Area of Rectangle is ", area)

class square:

m
def display(self):

er as
print("This is a Square")

co
eH w
def area(self, Side):
area = Side * Side

o.
print("Area of square is ", area)
rs e
ou urc
1. Handling Exceptions - 1
o

Exception handling 1.
aC s
v i y re

# Complete the 'Handle_Exc1' function below.

def Handle_Exc1():
a=int(input())
b=int(input())
ed d

c=a+b
ar stu

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:
sh is

print("All in range")
Th

1. Handling Exceptions - 2

Write the function definition for the function 'FORLoop'

# Complete the 'FORLoop' function below.

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

This study source was downloaded by 100000830658032 from CourseHero.com on 08-24-2021 03:48:19 GMT -05:00

https://www.coursehero.com/file/72192067/Python-3-Functions-and-OOPs-FPtxt/
print(next(iter1))
return iter1

Handling Exceptions 3

Bank_ATM

# Complete the 'Bank_ATM' function below.


#
# Define the Class for user-defined exceptions "MinimumDepositError" and
"MinimumBalanceError" here
class MinimumDepositError(Exception):
pass
class MinimumBalanceError(Exception):
pass

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

m
least 500"))

er as
if choice == 1:

co
if amount < 2000:

eH w
raise(MinimumDepositError("The Minimum amount of Deposit should be
2000."))

o.
else: rs e
balance+=amount
ou urc
print("Updated Balance Amount: ",balance)

if choice == 2:
if balance-amount < 500:
o

raise(MinimumBalanceError("You cannot withdraw this amount due to


aC s

Minimum Balance Policy"))


v i y re

else:
balance-=amount
print("Updated Balance Amount: ",balance)
ed d

Classes and Objects 2 - Task 1


ar stu

Inheritance - Parent and Children Shares

# It is expected to create two child classes 'son' & 'daughter' for the above
class 'parent'
sh is

#
#Write your code here
Th

# Parent class created


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
self.total = total

This study source was downloaded by 100000830658032 from CourseHero.com on 08-24-2021 03:48:19 GMT -05:00

https://www.coursehero.com/file/72192067/Python-3-Functions-and-OOPs-FPtxt/
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

Library Harry Potter

# Complete the 'Library' function below.

m
#

er as
co
eH w
def Library(memberfee,installment,book):
# Write your code here

o.
#print(memberfee) rs e
#print(installment)
ou urc
#print(book)

if installment > 3:
raise(ValueError("Maximum Permitted Number of Installments is 3"))
o
aC s

if installment == 0:
v i y re

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 ==


ed d

'prisoner of azkaban' or book == 'Goblet of Fire' or book == 'order of phoenix'


ar stu

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"))
sh is
Th

Python DateTime

# Complete the 'dateandtime' function below.


#
# The function accepts INTEGER val as parameter.
# The return type must be LIST.
#
import datetime
def dateandtime(val,tup):
# Write your code here

# tup = 1 and 4 : 3 values (year, month, date)

This study source was downloaded by 100000830658032 from CourseHero.com on 08-24-2021 03:48:19 GMT -05:00

https://www.coursehero.com/file/72192067/Python-3-Functions-and-OOPs-FPtxt/
# tup = 2 : single value (timestamp)
# tup = 3 : 3 values (hours, mins, secs)
# tup = 5: 5 values (year, month , date, hours, mins, secs)

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)

m
weekday = d.strftime('%A')

er as
list.append(weekday)

co
fullmonth = d.strftime('%B')

eH w
list.append(fullmonth)
day = d.strftime('%j')

o.
list.append(day) rs e
if val == 5:
ou urc
d = datetime.datetime(tup[0],tup[1],tup[2],tup[3],tup[4],tup[5])
list.append(d)
return list
o
aC s

Python - Itertools (NOT YET COMPLETED)


v i y re

#
# Complete the 'usingiter' function below.
#
# The function is expected to return a TUPLE.
ed d

# The function accepts following parameters:


ar stu

# 1. TUPLE tupb
#
import itertools
import operator
from itertools import chain
sh is

def performIterator(tuplevalues):
Th

# Write your code here


mainlist = list()
list1 = list()

for var in range(len(tuplevalues[0])):


list1.append(tuplevalues[0][var])

mainlist.append(list1[0:4])

list2 = list()

for var in range(len(tuplevalues[1])):


list2.append(tuplevalues[1][var])
num = int(list2[0])

tupcount = len(tuplevalues[1])

This study source was downloaded by 100000830658032 from CourseHero.com on 08-24-2021 03:48:19 GMT -05:00

https://www.coursehero.com/file/72192067/Python-3-Functions-and-OOPs-FPtxt/
rep = list(itertools.repeat(num,tupcount))
mainlist.append(rep)

tup3 = tuplevalues[2]

result = itertools.accumulate(tup3,operator.add)
list3 = list()

for each in result:


list3.append(each)

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)

m
only_odd = [num for num in list4 if num % 2 ==1]

er as
mainlist.append(only_odd)

co
mainlist = str(mainlist).replace('[','(').replace(']',')')

eH w
return(mainlist)

o.
rs e
ou urc
Python - Cryptography

#
# Complete the 'encrdecr' function below.
o

#
aC s

# The function is expected to return a LIST.


v i y re

# The function accepts following parameters:


# 1. STRING keyval
# 2. STRING textencr
# 3. Byte-code textdecr
#
ed d

from cryptography.fernet import Fernet


ar stu

def encrdecr(keyval, textencr, textdecr):


res = []
cipher = Fernet(keyval)
encrval = cipher.encrypt(textencr)
sh is

res.append(encrval)
decrbytes = cipher.decrypt(textdecr)
Th

res.append(decrbytes.decode('utf8'))
return res

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

This study source was downloaded by 100000830658032 from CourseHero.com on 08-24-2021 03:48:19 GMT -05:00

https://www.coursehero.com/file/72192067/Python-3-Functions-and-OOPs-FPtxt/
# 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)

Python - Collections - NOT COMPLETED

m
er as
co
#

eH w
# Complete the 'collectionfunc' function below.
#

o.
# The function accepts following parameters:
rs e
# 1. STRING text1
ou urc
# 2. DICTIONARY dictionary1
# 3. LIST key1
# 4. LIST val1
# 5. DICTIONARY deduct
o

# 6. LIST list1
aC s

#
v i y re

import collections

def collectionfunc(text1, dictionary1, key1, val1, deduct, list1):


# Write your code here
ed d

tmp = list()
ar stu

mydict = dict()
li = list(text1.split(" "))

items = collections.Counter(li)
y = sorted(items.items())
sh is

fix = str(y).replace('[(', '{').replace(')]',


'}').replace('\',','\':').replace('), (',', ')
Th

print(fix)

items = collections.Counter(dictionary1)

res1 = {key: items[key] - deduct.get(key, 0) for key in items.keys()}


res2 = {key: items[key] - deduct.get(key, 0) for key in deduct.keys()}
res = {**res1, **res2}
print(res)

keyval = dict(zip(key1, val1))


count = int()
for k,v in keyval.items():
count += 1
if count == 2:
keyval.pop(k)
break

This study source was downloaded by 100000830658032 from CourseHero.com on 08-24-2021 03:48:19 GMT -05:00

https://www.coursehero.com/file/72192067/Python-3-Functions-and-OOPs-FPtxt/
keyval.update([(k, v)])
print(keyval)

even=list()
odd=list()

for i in list1:
if (i % 2) == 0:
even.append(i)
else:
odd.append(i)

oedict = {}

if len(odd) > 0 and len(even) > 0:


print("{'odd': " + str(odd) + ", 'even': " + str(even) + "}")
elif len(odd) == 0 and len(even) > 0:
print("{'even': " + str(even) + "}")
elif len(odd) > 0 and len(even) == 0:
print("{'odd': " + str(odd) + "}")
else:
print(oedict)

m
er as
co
eH w
o.
rs e
ou urc
o
aC s
v i y re
ed d
ar stu
sh is
Th

This study source was downloaded by 100000830658032 from CourseHero.com on 08-24-2021 03:48:19 GMT -05:00

https://www.coursehero.com/file/72192067/Python-3-Functions-and-OOPs-FPtxt/
Powered by TCPDF (www.tcpdf.org)

You might also like