Python OOP Functions

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Hands On 1

----------
task 1
---------
zenPython='''The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.'''
L=zenPython.split()
print(len(L))
print(L)

taks 2
-------
k=[]
for w in L:
k.append(w.strip(" ,.-*!"))
L=k
print(L[3])

task 3
------
L=[w.lower() for w in L]
print(L[3])

task 4
------
u=set(L)
print(len(u))

task 5
------
*** this task can be done easily using nltk for that before clicking on vim app.py
enter the comand " pip install --user nltk " wait for a few secs to download and
install nltk (more about this package is on NLP using python course) , then click
on vim app.py ***

import nltk
word_frequency=nltk.FreqDist(L)
print((word_frequency["the"]))

task6

This study source was downloaded by 100000786139973 from CourseHero.com on 06-14-2022 03:32:33 GMT -05:00

https://www.coursehero.com/file/60104772/Python-OOP-functionstxt/
------
w=dict(word_frequency)
fw= [x for x in list(w.items()) if x[1]>5]
print(len(fw))

Hands on 2
--------

def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a+b
fs=fibonacci()
print(next(fs))
print(next(fs))
print(next(fs))
print(next(fs))

Hands on 3
---------
def fact_gen():
yield(0)
yield(1)
a,b=1,2
while True:
yield(a*b)
a,b=b,b+1

fs=fact_gen()
print(next(fs))
print(next(fs))
print(next(fs))
print(next(fs))

Hands on 4
-----------
Task 1
------
class Point:
def __init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
p1=Point(4,2,9)
print(p1)

Task 2
-------
class Point:
def __init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
def __str__(self):
return 'point: ({self.x} {self.y} {self.z})'.format(self=self)

This study source was downloaded by 100000786139973 from CourseHero.com on 06-14-2022 03:32:33 GMT -05:00

https://www.coursehero.com/file/60104772/Python-OOP-functionstxt/
p1=Point(4,2,9)
print(p1)

Task 3
-------
import math
class Point:
def __init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
def __str__(self):
return 'point: ({self.x} {self.y} {self.z})'.format(self=self)
def distance(self,a):
dist = math.sqrt( (self.x-a.x)**2 + (self.y-a.y)**2 + (self.z-a.z)**2 )
return dist
p1=Point(4,5,6)
p2=Point(-2,-1,4)
print(p1.distance(p2))

Task 4
--------
import math
class Point:
def __init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
def __str__(self):
return 'point: ({self.x} {self.y} {self.z})'.format(self=self)
def distance(self,a):
dist = math.sqrt( (self.x-a.x)**2 + (self.y-a.y)**2 + (self.z-a.z)**2 )
def __add__(self,a):
add=Point(self.x+a.x,self.y+a.y,self.z+a.z)
return add
p1=Point(4,5,6)
p2=Point(-2,-1,4)
print(p1+p2)

Hands on 5
-----------
Task 1
-------
def iseven(a):
if a%2==0:
return True
else:
return False
print(iseven(43))

Task 2
------
import unittest
class TestIsEvenMethod(unittest.TestCase):
def iseven(a):
if a%2==0:
return True
else:

This study source was downloaded by 100000786139973 from CourseHero.com on 06-14-2022 03:32:33 GMT -05:00

https://www.coursehero.com/file/60104772/Python-OOP-functionstxt/
return False
def test_isEven1(self):
self.assertEqual(iseven(5),False)
unittest.main()

Task 3
------
import unittest
class TestIsEvenMethod(unittest.TestCase):
def iseven(a):
if a%2==0:
return True
else:
return False
def test_isEven1(self):
self.assertEqual(iseven(5),False)
def test_isEven2(self):
self.assertEqual(iseven(10),True)
unittest.main()

Task 4
------
import unittest
class TestIsEvenMethod(unittest.TestCase):
def iseven(a):
if a%2==0:
return True
else:
return False
def test_isEven1(self):
self.assertEqual(iseven(5),False)
def test_isEven2(self):
self.assertEqual(iseven(10),True)
def test_isEven3(self):
self.assertRaises("hello",TypeError)

unittest.main()

Hands on 6
----------

n=int(input("enter a num"))
try:
if n<0 or n>100:
raise ValueError
except ValueError:
print("Input integer value must be between 0 and 100.")

Hands on 7
---------

n=input("enter a String")
try:
if len(n)>10:
raise ValueError
else:
print(n)
except ValueError:

This study source was downloaded by 100000786139973 from CourseHero.com on 06-14-2022 03:32:33 GMT -05:00

https://www.coursehero.com/file/60104772/Python-OOP-functionstxt/
print("Input String contains more than 10 characters.")

Hands on 8
----------
import os
try:
if not os.path.isfile("unknown_file.txt"):
raise FileNotFoundError
except:
print("File not found")

Hands on 9
----------

class Circle(Exception):
def __init__(self,r):
try:
if not isinstance(r, int):
raise RadiusInputError
else:
self.radius=r
except:
print("hello' is not a number")
c=Circle("hello")

Hands on 11
----------
import os

for files in os.walk(".", topdown=False):


for name in files:
if ".py" in str(name):
print(name)

Hands on 12
----------
import calendar

def find_five_sunday_months(year):
calendar.setfirstweekday(calendar.SUNDAY)
five_sunday_months = []
for month in range(1, 13):
calendar_month = calendar.monthcalendar(year, month)
# If you're counting Sunday as the first day of the week, then any month
that extends into
# six weeks, or starts on a Sunday and extends into five weeks, will
contain five Sundays.
if len(calendar_month) == 6 or (len(calendar_month) == 5 and
calendar_month[0][0] == 1):
five_sunday_months.append(calendar.month_abbr[month])

return five_sunday_months

print (find_five_sunday_months(2018))

Hands on 13
-----------

This study source was downloaded by 100000786139973 from CourseHero.com on 06-14-2022 03:32:33 GMT -05:00

https://www.coursehero.com/file/60104772/Python-OOP-functionstxt/
import timeit
f='''def f1():
L=[x for x in range(0,20)]
return L'''
f3='''def f2():
for n in range(0,20):
yield(n*n)
n+=1'''
print(timeit.timeit(stmt = f,number = 10000))
print(timeit.timeit(stmt = f3,number = 10000))

Hands on 14
----------
import pstats, cProfile

def f1(n1):
f= [i**2 for i in range(1,n1)]
return f

def f2(n2):
g = (x**2 for x in range(1,n2))
return g

cProfile.runctx("f1(n1)", globals(), {'n1':200001}, "Profile1.prof")


cProfile.runctx("f2(n2)", globals(), {'n2':200001}, "Profile2.prof")

s1 = pstats.Stats("Profile1.prof")
s1.strip_dirs().sort_stats("time").print_stats()

s2 = pstats.Stats("Profile2.prof")
s2.strip_dirs().sort_stats("time").print_stats()

The elements of an iterator can be accessed multiple times. False


What value does 'k' hold after executing the expression, k = [print(i) for i in
"maverick" if i not in "aeiou"]? a list of nones
What is the default return value of a Python function? none
Which of the following types of arguments can be passed to a function? All the
options
The output of expression, k = [print(i) for i in "maverick" if i not in "aeiou"] is
_______. Prints all characters that are not vowels
The output of the expression '2' == 2 is _________. False
Which of the keyword is used to display a customised error message to the user?
raise
Which of the following execption occurs, when an undefined object is accessed? Name
error
Which of the following exception occurs, when a number is divided by zero?
zerodivisionerror
XXX Can one block of except statements handle multiple exception? Yes, like except
( NameError, SyntaxError, ...)
In which of the following scenarios, finally block is executed? always
If a list has 5 elements, then which of the following exceptions is raised when 8th
element is accessed? index error
Which of the following modules are used to deal with Data compression and
archiving? All the options
Which of the following statement retreives names of all builtin objects? import
builtins; builtins.dict.keys()

This study source was downloaded by 100000786139973 from CourseHero.com on 06-14-2022 03:32:33 GMT -05:00

https://www.coursehero.com/file/60104772/Python-OOP-functionstxt/
Which of the following modules is used to manage installtion, upgradtion, deletion
of other pacakages automatically? pip
Which of the following module is not used for parsing command line arguments
automatically? cmdparse
Any Python Script can act like a Module. State if the statement is True or False?
True
Which of the following method is used by a user defined class to support '+'
operator? __add__
What is the output of the following code? class grandpa(object):
pass

class father(grandpa):
pass

class mother(object):
pass

class child(mother, father):


pass

print(child.__mro__)

Ans : (<class '__main__.child'>, <class '__main__.mother'>, <class


'__main__.father'>,
<class '__main__.grandpa'>, <class 'object'>)

Which of the following is not a way to import the module 'm1' or the functions 'f1'
and 'f2' defined in it? import f1, f2 from m1
The output of the expression [(i.upper(), len(i)) for i in 'kiwi' ] is _______.
[('K', 1), ('I', 1), ('W', 1), ('I', 1)]
Which keyword is used for defining a function? def
Which of the following methods of 'random' module is used to pick a single element,
randomly, from a given list of elements? choice
Which of the following keyword is necessary for defining a generator function?
yield
What is the output of the following code?

class A:
def __init__(self):
print('one')

def f(self):
print(float())
print(hex(-255))

class B(A):
def __init__(self):
print('two')

def f(self):
print(float())
print(hex(-42))

x = B()
x.f()

Ans
two
0.0

This study source was downloaded by 100000786139973 from CourseHero.com on 06-14-2022 03:32:33 GMT -05:00

https://www.coursehero.com/file/60104772/Python-OOP-functionstxt/
-0x2a

Which of the following keyword is used for creating a method inside a class? def
What is the output of the following code?

class A:
def __init__(self, x=5, y=4):
self.x = x
self.y = y

def __str__(self):
return 'A(x: {}, y: {})'.format(self.x, self.y)

def __eq__(self, other):


return self.x * self.y == other.x * other.y

def f1():
a = A(12, 3)
b = A(3, 12)
if (a == b):
print(b != a)
print(a)

f1()
Ans:False
A(x: 12, y: 3)
Which of the following expression can be used to check if the file 'C:\Sample.txt'
exists and is also a regular file? os.path.isFile(C:\Sample.txt)
Which of the following error occurs, if an iterator is accessed, when it has no
elements? Exhauseted
Which of the following statement retrieves names of all builtin module names?
import sys; sys.builtin_module_names
How are variable length keyword arguments specified in the function heading? One
star followed by a valid identifier

This study source was downloaded by 100000786139973 from CourseHero.com on 06-14-2022 03:32:33 GMT -05:00

https://www.coursehero.com/file/60104772/Python-OOP-functionstxt/
Powered by TCPDF (www.tcpdf.org)

You might also like