0% found this document useful (0 votes)
181 views7 pages

Python 3 Oops Hands On

This document contains code snippets and explanations related to Python hands-on exercises covering various topics: 1. String methods, regular expressions, collections module 2. Generators, prime number generator, complex number classes 3. Date/time functions, modules like itertools, cryptography 4. Exceptions, classes, inheritance for shapes, movies, banking transactions

Uploaded by

rajesh
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)
181 views7 pages

Python 3 Oops Hands On

This document contains code snippets and explanations related to Python hands-on exercises covering various topics: 1. String methods, regular expressions, collections module 2. Generators, prime number generator, complex number classes 3. Date/time functions, modules like itertools, cryptography 4. Exceptions, classes, inheritance for shapes, movies, banking transactions

Uploaded by

rajesh
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/ 7

Python 3 oops hands on

hands on-1 pyhton string methods

#not completely correct word1 is wrong


import collections

def stringmethod(para, special1, special2, list1, strfind):


# Write your code here
alphanumeric = ""

for character in para:


if character.isalnum() or character==" ":
alphanumeric += character

word1 = alphanumeric
rword2 = word1[:70][::-1]
print(rword2)

rword2.replace(" ", "")


list_string = list(rword2)
string = special2.join(list_string)
print(string)
if all(x in para for x in list1):
print("Every string in {} were present".format(list1))
else:
print("Every string in {} were not present".format(list1))
li2 = word1.split()
print(li2[:20])
print([item for item, count in collections.Counter(li2).items() if count <
3][-20:])
print(word1.rindex(strfind)+1 )

#magic constant Generator

#!/bin/python3

import math
import os
import random
import re
import sys

#100 PERCENT WORKING


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

def generator_Magic(n1):

for i in range(3, n1+1):


n2 = i*i
n3 = n2 + 1
n4 = i * n3
M = n4/2
yield M

This study source was downloaded by 100000840792620 from CourseHero.com on 03-21-2022 02:03:21 GMT -05:00

https://www.coursehero.com/file/72432972/python-3-oops-hands-ontxt/
Python Prime generator -working

def primegenerator(num1, val):


n = num1
primes = []

for i in range(2, n + 1):


for j in range(2, int(i ** 0.5) + 1):
if i%j == 0:
break
else:
primes.append(i)

res_even = primes[::2]
res_odd = primes[1::2]
if(val == 1):
for i in res_even:
yield i
else:
for i in res_odd:
yield i

Classes and objects 1task 1 #working

class Movie:

def __init__(self,name, n,cost):


self.name = name
self.n = n
self.cost = cost

def __str__(self):
k = "Movie : " + self.name + "\nNumber of Tickets : " + str(self.n) +
"\nTotal Cost : " + str(self.cost)

return k

Classes and objects 1 task 2 #working 100


class comp:

def __init__(self, real, img):


self.real = real
self.img = img

def add(self, sec):


r = self.real + sec.real
i = self.img + sec.img
k = "Sum of the two Complex numbers :{}+{}i".format(r, i)
print(k)
def sub(self, sec):
r = self.real - sec.real
i = self.img - sec.img
if i < 0:
k = "Subtraction of the two Complex numbers :{}{}i".format(r, i)
else:
k = "Subtraction of the two Complex numbers :{}+{}i".format(r, i)

print(k)

This study source was downloaded by 100000840792620 from CourseHero.com on 03-21-2022 02:03:21 GMT -05:00

https://www.coursehero.com/file/72432972/python-3-oops-hands-ontxt/
Classes and objects 2 task 1 #working
class son(parent):
def __init__(self, parent, percentage):
super().__init__(parent)
self.Percentage_for_son = percentage

def son_display(self):
s = round((self.total_asset * self.Percentage_for_son)/100 ,2)
print("Share of Son is "+str(s)+" Million.")

class daughter(parent):
def __init__(self, parent, percentage):
super().__init__(parent)
self.Percentage_for_daughter = percentage

def daughter_display(self):
s = round((self.total_asset * self.Percentage_for_daughter)/100 ,2)
print("Share of Daughter is "+str(s)+" Million.")

Classes and objects 2 task 2 #working


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

def area(self, l, b):


print("Area of Rectangle is {}".format(l*b))

class square:
def display(self):
print("This is a Square")

def area(self, side):


print("Area of square is {}".format(side*side))

hands on python date and time


Python 3 - Functions and OOPs | 10 | Modules 1

Python date time


from datetime import datetime
import calendar

def dateandtime(val,tup):
# Write your code here
# Write your code here
list = []
if val == 1:
dt = datetime(tup[0], tup[1], tup[2])
dt = dt.date()
list.append(dt)
st = dt.strftime("%d/%m/%Y")
list.append(st)
return list

if val == 2:
dt_object = datetime.fromtimestamp(tup[0])
list.append(dt_object.date())
return list

if val== 3:

This study source was downloaded by 100000840792620 from CourseHero.com on 03-21-2022 02:03:21 GMT -05:00

https://www.coursehero.com/file/72432972/python-3-oops-hands-ontxt/
# print(tup)
tim = datetime(2020,1,1,tup[0], tup[1], tup[2])
tim = tim.time()
list.append(tim)
f = tim.strftime('%I')
list.append(f)
return list
if val == 4:
dt = datetime(tup[0], tup[1], tup[2])
weekday = dt.weekday()
list.append(calendar.day_name[weekday])
month_name = datetime.date(dt).strftime('%B')
list.append(month_name)
j = datetime.date(dt).strftime("%j")
list.append(j)
return list
if val == 5:
dt = datetime(tup[0], tup[1], tup[2], tup[3], tup[4], tup[5])
list.append(dt)
return list

#Python 3 - Functions and OOPs | 11 | Modules 2

import itertools
import operator
from itertools import chain

def p(a, b):


return a+b
def performIterator(tuplevalues):
# Write your code here

main_list = []
another_list = []

cycler = itertools.cycle(tuplevalues[0])
start=0
end = 4
for out in cycler:
if(start != end):
another_list.append(out)
start += 1
else:
break

d = tuple(another_list)
main_list.append(d)
d = tuple(itertools.repeat(tuplevalues[1][0], len(tuplevalues[1])))
main_list.append(d)
# using the itertools.accumulate()

result = itertools.accumulate(list(tuplevalues[2]),
p)
# printing each item from list
l = []
for each in result:
l.append(each)
main_list.append(tuple(l))

res = list(chain.from_iterable(tuplevalues))
main_list.append(tuple(res))
out = []

This study source was downloaded by 100000840792620 from CourseHero.com on 03-21-2022 02:03:21 GMT -05:00

https://www.coursehero.com/file/72432972/python-3-oops-hands-ontxt/
for num in res:

# checking condition
if num % 2 != 0:
out.append(num)

main_list.append(tuple(out))

return tuple(main_list)

#working
excep 3:

class MinimumDepositError(Exception):
pass
class MinimumBalanceError(Exception):
pass

def Bank_ATM(bal,ch,amt):
# Write your code here

if bal < 500:


raise ValueError('As per the Minimum Balance Policy, Balance must be at
least 500')

if ch == 1:
if amt < 2000:
raise MinimumDepositError('The Minimum amount of Deposit should be
2000.')
else:
bal = bal + amt
elif ch == 2:
b = bal - amt
if b < 500:
raise MinimumBalanceError('You cannot withdraw this amount due to
Minimum Balance Policy')
else:
bal = bal - amt
print('Updated Balance Amount: ', end ="")
print(bal)

#python 3 - Functions and OOPs | 12 | Modules 3

#
# 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
def encrdecr(keyval, textencr, textdecr):
# Write your code here
main_list = []
f = Fernet(keyval)
token = f.encrypt(textencr)
main_list.append(token)
token = f.decrypt(textdecr)
token = token.decode("utf-8")
main_list.append(token)

This study source was downloaded by 100000840792620 from CourseHero.com on 03-21-2022 02:03:21 GMT -05:00

https://www.coursehero.com/file/72432972/python-3-oops-hands-ontxt/
return main_list

#Modules 4 full working


# Modules 4
import calendar
from datetime import datetime
from collections import Counter
def usingcalendar(datetuple):
# Write your code here
v = datetime(datetuple[0],datetuple[1],datetuple[2])
if(calendar.isleap(v.year)):
v = v.replace(month=2)

print(calendar.month(v.year, v.month))
calen = calendar.Calendar()
i = calen.itermonthdays3(v.year, v.month)
main_list = []
for each in i:
vi = datetime(each[0],each[1],each[2])
if vi.month == v.month or vi.month == v.month +1 or vi.year == v.year
+1:
vi = vi.date()
main_list.append(vi)

print(main_list[-7:])

count = Counter(d.strftime('%A') for d in calen.itermonthdates(v.year,


v.month) if d.month==v.month)
print(count.most_common(1)[0][0])

#Modules 5

from collections import Counter


from collections import OrderedDict
def collectionfunc(text1, dictionary1, key1, val1, deduct, list1):
# Write your code here

count = Counter(text1.split())
dic = dict(count)
dict1 =dict( OrderedDict(sorted(dic.items())) )
print(dict1)
count = Counter(dictionary1)
res = {key: count[key] - deduct.get(key, 0) for key in count.keys()}
print(res)
zip_iterator = zip(key1, val1)
a_dict = dict(zip_iterator)
a_dictionary = dict( OrderedDict(sorted(a_dict.items())) )
del a_dictionary[key1[1]]
a_dictionary[key1[1]] = val1[1]
print(a_dictionary)

four test cases failing

from collections import Counter


from collections import OrderedDict
from collections import defaultdict

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

This study source was downloaded by 100000840792620 from CourseHero.com on 03-21-2022 02:03:21 GMT -05:00

https://www.coursehero.com/file/72432972/python-3-oops-hands-ontxt/
# Write your code here

count = Counter(text1.split())
dic = dict(count)
dict1 =dict( OrderedDict(sorted(dic.items())) )
print(dict1)
count = Counter(dictionary1)
deduct = Counter(deduct)
res = {key:count[key] - deduct.get(key, 0) for key in count}
count.subtract(deduct)
print(dict(count))
zip_iterator = zip(key1, val1)
a_dict = dict(zip_iterator)
a_dictionary = dict( OrderedDict(sorted(a_dict.items())) )
del a_dictionary[key1[1]]
a_dictionary[key1[1]] = val1[1]
print(a_dictionary)
sd = defaultdict(list)
for i in list1:
if i%2==0:
sd['even'].append(i)
else:
sd['odd'].append(i)
print(dict(sd))

This study source was downloaded by 100000840792620 from CourseHero.com on 03-21-2022 02:03:21 GMT -05:00

https://www.coursehero.com/file/72432972/python-3-oops-hands-ontxt/
Powered by TCPDF (www.tcpdf.org)

You might also like