Professional Documents
Culture Documents
in/
What will be the output for the following code -
>>> list1 = [2, 33, 222, 14, 25]
>>> list1[::-1]
Error
25
Given;
In []: a = [1, 2, 5, 9]
How do you find the length of this list?
length(a)
a.length()
len(a)
a.size()
Write a python script to print the odd numbers from 1 to 10 using a while loop.
Undo Changes
1
i=1
2
while i<11:
3
print(i)
4
i=i+2
Write a python script which will accept an integer as user input (Please do
not add any prompt while taking input).
If the number is even print Even
If the number is odd print Odd.
Example 1:-
Input
2
Output
Even
Example 2:-
Input
3
Output
Odd
a=int(input())
if a%2==0:
print('Even')
else :
print('Odd')
The function must return a list containing two values. The first value of the list
will be the sum of all the odd values between (and including) start and stop.
The second value of the list will be the sum of all the even values between
(and including) start and stop.
s1=0,s2=0
if i%2==0:
s1=s1+i
else :
s2=s2+i
return s2,s1
AD - Practice Function Exercise
Write a function called prod that can be called with any number of arguments (at
least one) but computes the product of all the given values as seen below.
For Example:
Input:
prod(2., 2.)
Output:
4.0
Input:
prod(1, 2, 3)
Output:
6
def prod(*args):
res=1.0
for x in args:
res*=x
return res
return x*2
def apply(twice,*r):
y=[]
for i in r:
y.append(twice(i))
return y
return len(r)
return sorted(r.keys())
Write a function called power that is given a single integer and returns a function
that takes a single number but returns its power.
For Example:
Input:
pow2 = power(2)
pow2(2)
Output:
4
Input:
pow2(4)
Output:
16
Input:
pow3 = power(3)
pow3(2)
Output:
8
def power(n):
def g(x):
return x**n
return g
Write a function called debug that takes any function as a single positional
argument but returns a function that first prints out the arguments passed to
the function before calling it and returning its value.
For Example:
Input:
debug(max)(1, 2)
Output:
(1, 2) {}
2
Input:
import math
debug(math.sin) (1.0)
Output:
(1.0,) {}
1
def debug(f):
def g(*a,**k):
print(a,k)
return f(*a,**k)
return g
OOP Exercise 1
Create the simplest possible class, called Simple, which has no attributes or
methods. Try this out on your own IPython interpreters. You should be able to
instantiate it as follows
Input:
s = Simple()
class Simple :
pass
Create a simple Personclass with two arguments: a name (a string) and an age(a
float). To be used as follows:
For Example:
Input:
p = Person('Arun', 22.0)
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
Create a simple Person class with two attribute a name and an age. However, let the
name default to the string 'name' and the age default to 0.0.
For Example:
Input:
p = Person()
print(p.name, p.age)
Output:
name 0.0
class Person:
def __init__(self,name='name',age=0.0):
self.name=name
self.age=age
def __init__(self,name='name',age=0.0):
self.name=name
self.age=age
def birthday(self):
print("HBD",self.name)
self.age+=1.0
OOP Exercise 2
Create a simple Point class with class attributes x, y that defaults to 0.0
For example:
Input:
p = Point()
p.x, p.y
Output:
(0.0, 0.0
class Point:
x=0.0
y=0.0
Create a simple Point clas with instance attributes x, y but add a class
method polar(r, theta) that takes coordinates in (r, θ) form but returns a
suitable point. Remember that, x = rcos(θ), y = rsin(θ).
For example:
Input:
p = Point.polar(1.0, 0.0)
p.x, p.y
Output:
(1.0, 0.0)
from math import sin, cos
class Point:
def __init__(self,x=0,y=0):
self.x=x
self.y=y
@classmethod
def polar(cls,r,th):
return cls(r*cos(th),r*sin(th))
AD - OOP Exercise 3
def __init__(self,x=0,y=0):
self.x=x
self.y=y
def __str__(self):
return '(%s,%s)'%(self.x,self.y)
def __repr__(self):
AD - OOP Exercise 4
Create an Animal class with name (str) and weight (float) attribute. Allow a user to
perform rich comparisons of animals based on their weight (it should support
all comparisons)
For exmaple:
Input:
cat = Animal('cat', 5)
dog = Animal('dog', 10)
dog > cat
Output:
True
class Animal:
def __init__(self,name,weight=0.0):
self.name=name
self.weight=weight
def __lt__(self,other):
def __le__(self,other):
def __eq__(self,other):
def __gt__(self,other):
def __ge__(self,other):
Write a Point class with two instance attributes x, y. Make it possible to add and
subtract two points. Also allow abs() to be callabe on a point.
from math import sqrt
class Point:
def __init__(self,x=0,y=0):
self.x=x
self.y=y
def __add__(self,other):
return Point(self.x+other.x,self.y+other.y)
def __sub__(self,other):
return Point(self.x-other.x,self.y-other.y)
def __abs__(self):
return sqrt((self.x*self.x+self.y*self.y))
Create a Zoo class which can contain animals. The Zoo should behave like a
container.
For example:
Input:
a = Animal('cat', 5)
b = Animal('dog', 10)
zoo = Zoo(a, b)
len(zoo)
a in zoo
Output:
2
True
class Animal:
def __init__(self,name,weight=0.0):
self.name=name
self.weight = weight
class Zoo:
def __init__(self,*animals):
self.animals=list(animals)
def __len__(self):
return len(self.animals)
def __contains__(self,item):
def __getitem__(self,key):
return self.animals[key]
def __iter__(self):
return self.animals
Quiz
p.kwargs[keys]
p.keys()
p.kwargs.keys()
x = [1, 2, 3]
y = x
y[1] = 9
None of above
[1, 9, 3]
[1, 2, 3]
[1, 3]
Select the correct syntax to get the output in junk = [1,2,3,4,5]
first , *junk, last = range(7)
12
Unpack error
24
return sorted(n)
Write a function rate(x) which returns a function that calculates the value of
the amount passed to that function with respect to the value of x passed to the
rate function.
Note: Use the same variables as mentioned in the Example below
Example:
>>> convert = rate(64)
>>> convert(5)
>>> 320
def rate(x):
def convert(y):
return y*x
return convert
Write a class Student to take name, age, blood_group and gender. Initial values of the
Student should be as follows
{‘Ram’, 20, O+ve, Male}
class Student:
def __init__(self,name='Ram',age=20,blood_group='O+ve',gender='Male'):
self.name=name
self.age=age
self.blood_group=blood_group
self.gender=gender
def f(t):
print(min(t))
def perform(f,*x):
f(x)
Select all possible options which can be written for keyword arguments in a function.
print(x)
def greet(func):
def new_func(*arg,**kw):
print("hello")
return (func(*args,**kw))
return new_func
def greet(func):
@wraps(func)
print("Hello")
result=func(*args,**kw)
print('goodbye')
return result
return new_func
# do not edit the code below
@greet
def f(x):
print(x)
Write a decorator called debug() that prints the name of the function before it
is called. Hint: Recall __name__
For example:
Input:
my_func(1)
Output
my_func
1
from functools import wraps
def debug(func):
@wraps(func)
def new_func(*args,**kw):
print(func.__name__)
return func(*args,**kw)
return new_func
@debug
def my_func(x):
print(x)
Write a decorator called debug(f, message=' ') that prints the name of the
function before it is called along with an optional message.
For example:
@debug(message='DEBUG: ')
def my_func(x):
print(x)
my_func(1)
Output
DEBUG: my_func
1
from functools import wraps
def debug(func=None,message=''):
def wrapper(func):
@wraps(func)
def new_func(*args,**kw):
if message:
print(message,func.__name__)
else:
print(func.__name__)
return func(*args,**kw)
return new_func
if func:
return wrapper(func)
else :
return wrapper
@debug(message='DEBUG:')
def my_func(x):
print(x)
f = input()
my_func(f)
Write a decorator called counter that keeps track of the number of times a
decorated function is called. Write another function
called show_counts() which lists all the called functions.
For example:
Input:
>> @counter
...def sq(x): return x*x
>> @counter
...def g(x): return x+2
>> for i in range(10): g(sq(i))
>> show_counts()
Output
sq: 10
g: 10
from functools import wraps
_counter_data={}
def counter(func):
@wraps(func)
def new_func(*args,**kw):
if func in _counter_data:
_counter_data[func]+=1
else:
_counter_data[func]=1
return func(*args,**kw)
return new_func
def show_counts():
pass
Decorator Qiz
Inorder to prevent missing doc strings in a decoratored function, which function should
be imported?
import wraps
Which of the below given method is used to get order of calls in multiple inheritance?
mor()
mro()
mcr()
Is Hierarchical Inheritance possible in Python?
No
Yes
Write a decorator called testdeco which takes a argument named power with
default value as 2 and use the power with argument passed to the decorated
function.
The decorated function testfunc should return the output
from functools import wraps
def testdeco(func,power=2):
@wraps(func)
def new_func(*arg,**kw):
print(power**power)
return func(*arg,**kw)
return new_func
@testdeco
def testfunc():
pass
Write a function called second_max that can be called with any number of
arguments, minimum of two. second_max should return second maximum of
all the given numbers.
def test(*n):
x=sorted(n)
return x[-2]
Which of this is a correct way to get numbers divisible by 3 in range 1 to 10 using list
comprehension method.
Using dictionary comprehension method where given a word, each character should
have it's position as key. Select the right syntax out of the options given below.
Example
Input: Hello
Output: {0: 'H', 1: 'e', 2: 'l', 3: 'l', 4: 'o'}