You are on page 1of 19

https://yaksh.fossee.

in/
What will be the output for the following code -
>>> list1 = [2, 33, 222, 14, 25]
>>> list1[::-1]

[25, 14, 222, 33, 2]

[2, 33, 222, 14]

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.

Note: You have already attempted this question successfully


Write your program below:

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

Write a function odd_even_sum(start, stop) that accepts two integer arguments.

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.

For Example: (Note: The values between 2 and 7 will be 2,3,4,5,6,7)


>>> odd_even_sum(2, 7)
>>> (15, 12)
def odd_even_sum(start, stop):

s1=0,s2=0

for i in range(start, stop+1):

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

Write a function called apply which takes a function followed by an arbitary


number of arguments and returns a list with the function applied to all the
arguments as shown below.
For Example:
Input:
apply(twice,1, 2)
Output:
[2, 4]
Input:
apply(twice, 1, 2, 3)
Output:
[2, 4, 6]
def twice(x):

return x*2

def apply(twice,*r):

y=[]

for i in r:

y.append(twice(i))

return y

Write a function called nkw that takes an arbitrary number of keyword


arguments and returns the number of keyword arguments passed.
For Example:
Input:
nkw(x=1, y=2)
Output:
2
Input:
nkw()
Output:
0
Input:
nkw(x=1)
Output:
1
def nkw(**r):

return len(r)

Write a function called kwname that takes an arbitary number of keyword


arguments and returns a sorted list of the keyword arguments passed.
For Example:
Input:
kwname(x=1, y=2)
Output:
['x', 'y']
Input:
kwname(z=1, a=2)
Output:
['a', 'z']
Input:
kwname()
Output:
[]
def kwname(**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

Create a simple Personclass with two attribute as before. Add a method


called birthday which takes no arguments and which prints 'HBD < name >'and
also increase the age by 1.
Note:
The < name > is the name of the instance.
For Example:
Input:
p = Person(name='Ram')
p.birthday()
p.age
Output:
HBD Ram
1.0
class Person:

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

Write a Point class with two attributes x, y withh useful __str__,


__repr__ methods as follows.
For example:
Input:
p = Point(1, 2)
str(p)
repr(p)
Output:
'(1,2)'
'Point(1, 2)'
class Point:

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

return 'Point(%s,%s)' % (self.x,self.y)

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

return self.weight < other.weight

def __le__(self,other):

return self.weight <= other.weight

def __eq__(self,other):

return self.weight == other.weight

def __gt__(self,other):

return self.weight > other.weight

def __ge__(self,other):

return self.weight >= other.weight


def __ne__(self,other):

return self.weight !=other.weight

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

return item in self.animals

def __getitem__(self,key):

return self.animals[key]

def __iter__(self):

return self.animals

Quiz

How to get keys for the following code?


class P:
def __init__(self, **kwargs):
self.kwargs = kwargs
p = P(a=1, b = 3, c= 4)
p.kwargs.key()

p.kwargs[keys]

p.keys()

p.kwargs.keys()

x = [1, 2, 3]
y = x
y[1] = 9

What is the output of x?

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)

first, junk, *last = range(7)

first, junk, last = range(7)

*first, junk, last = range(7)


What will be the output for following code?
x = [1, 2, 3, 4]
def func(a,b):
print(a*2, b*2)
func(*x[:2])

12

Unpack error

24

a and b not defined


Write a function named test() to take list of arguments/positional arguments,
sort them and return
def test(*n):

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

Write a function named perform() to take another function as argument and


call that function using the tuple passed with the perform() function.
Example:
>>> perform(min)(1,2,3,4)
>>> 1

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.

def test(**var): pass

def test(*args): pass

def test(***kwargs): pass

def test(**kwargs): pass


Write a decorator called greet that prints 'Hello' before the function is called.
For example:
@greet
def f(x):
print(x)
Input:
f(1)
Output
Hello
1
def f(x):

print(x)

def greet(func):

def new_func(*arg,**kw):

print("hello")

return (func(*args,**kw))

return new_func

Modify decorator greet to print "goodbye" after executing the function.


For example:
Input:
f(1)
Output
Hello
1
goodbye
from functools import wraps

def greet(func):

@wraps(func)

def new_func(*args, **kw):

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

# do not change the code below

@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

# do not change the code below

@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

from functools import reduce

from functools import wraps

from functools import total_ordering

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

Is possible only if inherited from a module


Write a decorator called deco Decorate a function called test
The decorated function should take an argument and add 1 to it.
Hint: Python version 3. Use all the function names given as it is, the argument
will be int.
def deco(func,x=0):
return x+1
@deco
def test():
pass

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]

Write a function named perform() to take another function as argument and


call that function using the tuple passed with the perform() function.
Example:
>>> perform(min)(1,2,3,4)
>>> 1

Which of this is a correct way to get numbers divisible by 3 in range 1 to 10 using list
comprehension method.

[x for x in range(1,11) if x%3!=0]

[x for x in range(1,11) if x%3==0]

[x for x in range(0,10) if x%3==0]

[x for x in range(1,11) if y%3==0]


Which of the following is the correct syntax of list comprehension to print a list
which has all unique combination except similar characters
Example for word="FOSSEE" output should be ['FO', 'FS', 'FS', 'FE', 'FE',
'OF', 'OS', 'OS', 'OE', 'OE', 'SF', 'SO', 'SE', 'SE', 'SF', 'SO', 'SE', 'SE', 'EF',
'EO', 'ES', 'ES', 'EF', 'EO', 'ES', 'ES']
x + y for x in word for y in word if x==y]

[x + y for x in word for y in word if x!y]

[x + y for x in word for y in word if x!=y]

[x + y for x in word for y in word]

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'}

{x:y for x, y in (word)}

{x:y for x, y in enumerate(word)}

{x+y for x, y in enumerate(word)}

{[x:y] for x, y in enumerate(word)}

You might also like