Vous êtes sur la page 1sur 144

Python :

Boxed values are data structures that are minimal wrappers around primitive types*. Boxed
values are typically stored as pointers to objects on the heap.

Thus, boxed values use more memory and take at minimum two memory lookups to access: once
to get the pointer, and another to follow that pointer to the primitive. Obviously this isn't the kind
of thing you want in your inner loops. On the other hand, boxed values typically play better with
other types in the system. Since they are first-class data structures in the language, they have the
expected metadata and structure that other data structures have.

In Java and Haskell generic collections can't contain unboxed values. Generic collections in
.NET can hold unboxed values with no penalties. Where Java's generics are only used for
compile-time type checking, .NET will generate specific classes for each generic type
instantiated at run time.

Java and Haskell have unboxed arrays, but they're distinctly less convenient than the other
collections. However, when peak performance is needed it's worth a little inconvenience to avoid
the overhead of boxing and unboxing.

* For this discussion, a primitive value is any that can be stored on the call stack, rather than
stored as a pointer to a value on the heap. Frequently that's just the machine types (ints, floats,
etc), structs, and sometimes static sized arrays. .NET-land calls them value types (as opposed to
reference types). Java folks call them primitive types. Haskellions just call them unboxed.

** I'm also focusing on Java, Haskell, and C# in this answer, because that's what I know. For
what it's worth, Python, Ruby, and Javascript all have exclusively boxed values. This is also
known as the "Everything is an object" approach***.

*** Caveat: A sufficiently advanced compiler / JIT can in some cases actually detect that a value
which is semantically boxed when looking at the source, can safely be an unboxed value at
runtime. In essence, thanks to brilliant language implementors your boxes are sometimes free.

15 Essential Python Interview Questions

Introduction
Looking for a Python job? Chances are you will need to prove that you know how to work with
Python. Here are a couple of questions that cover a wide base of skills associated with Python.
Focus is placed on the language itself, and not any particular package or framework. Each
question will be linked to a suitable tutorial if there is one. Some questions will wrap up multiple
topics.

I haven't actually been given an interview test quite as hard as this one, if you can get to the
answers comfortably then go get yourself a job.

What This Tutorial Is Not


This tutorial does not aim to cover every available workplace culture - different employers will
ask you different questions in different ways; they will follow different conventions; they will
value different things. They will test you in different ways. Some employers will sit you down in
from of a computer and ask you to solve simple problems; some will stand you up in front of a
white board and do similar; some will give you a take home test to solve; some will just have a
conversation with you.

The best test for a programmer is actually programming. This is a difficult thing to test with a
simple tutorial. So for bonus points make sure that you can actually use the functionality
demonstrated in the questions. If you actually understand how to get to the answers well enough
that you can actually make use of the demonstrated concepts then you are winning.

Similarly, the best test for a software engineer is actually engineering. This tutorial is about
Python as a language. Being able to design efficient, effective, maintainable class hierarchies for
solving niche problems is great and wonderful and a skill set worth pursuing but well beyond the
scope of this text.

Another thing this tutorial is not is PEP8 compliant. This is intentional as, as mentioned before,
different employers will follow different conventions. You will need to adapt to fit the culture of
the workplace. Because practicality beats purity.

Another thing this tutorial isn't is concise. I don't want to just throw questions and answers at you
and hope something sticks. I want you to get it, or at least get it well enough that you are in a
position to look for further explanations yourself for any problem topics.

Want to ace your technical interview? Schedule a Technical Interview Practice Session with an
expert now!

Question 1
What is Python really? You can (and are encouraged) make comparisons to other technologies in
your answer
Answer

Here are a few key points:

Python is an interpreted language. That means that, unlike languages like C and its
variants, Python does not need to be compiled before it is run. Other interpreted
languages include PHP and Ruby.

Python is dynamically typed, this means that you don't need to state the types of variables
when you declare them or anything like that. You can do things like x=111 and then
x="I'm a string" without error

Python is well suited to object orientated programming in that it allows the definition of
classes along with composition and inheritance. Python does not have access specifiers
(like C++'s public, private), the justification for this point is given as "we are all adults
here"

In Python, functions are first-class objects. This means that they can be assigned to
variables, returned from other functions and passed into functions. Classes are also first
class objects

Writing Python code is quick but running it is often slower than compiled languages.
Fortunately Python allows the inclusion of C based extensions so bottlenecks can be
optimised away and often are. The numpy package is a good example of this, it's really
quite quick because a lot of the number crunching it does isn't actually done by Python

Python finds use in many spheres - web applications, automation, scientific modelling,
big data applications and many more. It's also often used as "glue" code to get other
languages and components to play nice.

Python makes difficult things easy so programmers can focus on overriding algorithms
and structures rather than nitty-gritty low level details.

Why This Matters:

If you are applying for a Python position, you should know what it is and why it is so gosh-darn
cool. And why it isn't o.O

Question 2
Fill in the missing code:

def print_directory_contents(sPath):
"""
This function takes the name of a directory
and prints out the paths files within that
directory as well as any files contained in
contained directories.

This function is similar to os.walk. Please don't


use os.walk in your answer. We are interested in your
ability to work with nested structures.
"""
fill_this_in

Answer
def print_directory_contents(sPath):
import os
for sChild in os.listdir(sPath):
sChildPath = os.path.join(sPath,sChild)
if os.path.isdir(sChildPath):
print_directory_contents(sChildPath)
else:
print(sChildPath)

Pay Special Attention

Be consistent with your naming conventions. If there is a naming convention evident in


any sample code, stick to it. Even if it is not the naming convention you usually use

Recursive functions need to recurse and terminate. Make sure you understand how this
happens so that you avoid bottomless callstacks

We use the os module for interacting with the operating system in a way that is cross
platform. You could say sChildPath = sPath + '/' + sChild but that wouldn't work
on windows

Familiarity with base packages is really worthwhile, but don't break your head trying to
memorize everything, Google is your friend in the workplace!

Ask questions if you don't understand what the code is supposed to do

KISS! Keep it Simple, Stupid!

Why This Matters:

Displays knowledge of basic operating system interaction stuff

Recursion is hella useful


Question 3
Looking at the below code, write down the final values of A0, A1, ...An.

A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
A1 = range(10)
A2 = sorted([i for i in A1 if i in A0])
A3 = sorted([A0[s] for s in A0])
A4 = [i for i in A1 if i in A3]
A5 = {i:i*i for i in A1}
A6 = [[i,i*i] for i in A1]

If you dont know what zip is don't stress out. No sane employer will expect you to memorize the
standard library. Here is the output of help(zip).

zip(...)
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence.

If that doesn't make sense then take a few minutes to figure it out however you choose to.

Answer
A0 = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} # the order may vary
A1 = range(0, 10) # or [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] in python 2
A2 = []
A3 = [1, 2, 3, 4, 5]
A4 = [1, 2, 3, 4, 5]
A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8,
64], [9, 81]]

Why This Matters

1. List comprehension is a wonderful time saver and a big stumbling block for a lot of
people

2. If you can read them, you can probably write them down

3. Some of this code was made to be deliberately weird. You may need to work with some
weird people

Question 4
Python and multi-threading. Is it a good idea? List some ways to get some Python code to run in
a parallel way.
Answer

Python doesn't allow multi-threading in the truest sense of the word. It has a multi-threading
package but if you want to multi-thread to speed your code up, then it's usually not a good idea
to use it. Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure
that only one of your 'threads' can execute at any one time. A thread acquires the GIL, does a
little work, then passes the GIL onto the next thread. This happens very quickly so to the human
eye it may seem like your threads are executing in parallel, but they are really just taking turns
using the same CPU core. All this GIL passing adds overhead to execution. This means that if
you want to make your code run faster then using the threading package often isn't a good idea.

There are reasons to use Python's threading package. If you want to run some things
simultaneously, and efficiency is not a concern, then it's totally fine and convenient. Or if you are
running code that needs to wait for something (like some IO) then it could make a lot of sense.
But the threading library won't let you use extra CPU cores.

Multi-threading can be outsourced to the operating system (by doing multi-processing), some
external application that calls your Python code (eg, Spark or Hadoop), or some code that your
Python code calls (eg: you could have your Python code call a C function that does the expensive
multi-threaded stuff).

Why This Matters

Because the GIL is an A-hole. Lots of people spend a lot of time trying to find bottlenecks in
their fancy Python multi-threaded code before they learn what the GIL is.

Question 5
How do you keep track of different versions of your code?

Answer:

Version control! At this point, you should act excited and tell them how you even use Git (or
whatever is your favorite) to keep track of correspondence with Granny. Git is my preferred
version control system, but there are others, for example subversion.

Why This Matters:

Because code without version control is like coffee without a cup. Sometimes we need to write
once-off throw away scripts and that's ok, but if you are dealing with any significant amount of
code, a version control system will be a benefit. Version Control helps with keeping track of who
made what change to the code base; finding out when bugs were introduced to the code; keeping
track of versions and releases of your software; distributing the source code amongst team
members; deployment and certain automations. It allows you to roll your code back to before
you broke it which is great on its own. Lots of stuff. It's just great.
Question 6
What does this code output:

def f(x,l=[]):
for i in range(x):
l.append(i*i)
print(l)

f(2)
f(3,[3,2,1])
f(3)

Answer
[0, 1]
[3, 2, 1, 0, 1, 4]
[0, 1, 0, 1, 4]

Hu?

The first function call should be fairly obvious, the loop appends 0 and then 1 to the empty list,
l. l is a name for a variable that points to a list stored in memory. The second call starts off by
creating a new list in a new block of memory. l then refers to this new list. It then appends 0, 1
and 4 to this new list. So that's great. The third function call is the weird one. It uses the original
list stored in the original memory block. That is why it starts off with 0 and 1.

Try this out if you don't understand:

l_mem = []

l = l_mem # the first call


for i in range(2):
l.append(i*i)

print(l) # [0, 1]

l = [3,2,1] # the second call


for i in range(3):
l.append(i*i)

print(l) # [3, 2, 1, 0, 1, 4]

l = l_mem # the third call


for i in range(3):
l.append(i*i)

print(l) # [0, 1, 0, 1, 4]

Question 7
What is monkey patching and is it ever a good idea?

Answer

Monkey patching is changing the behaviour of a function or object after it has already been
defined. For example:

import datetime
datetime.datetime.now = lambda: datetime.datetime(2012, 12, 12)

Most of the time it's a pretty terrible idea - it is usually best if things act in a well-defined way.
One reason to monkey patch would be in testing. The mock package is very useful to this end.

Why This Matters

It shows that you understand a bit about methodologies in unit testing. Your mention of monkey
avoidance will show that you aren't one of those coders who favor fancy code over maintainable
code (they are out there, and they suck to work with). Remember the principle of KISS? And it
shows that you know a little bit about how Python works on a lower level, how functions are
actually stored and called and suchlike.

PS: it's really worth reading a little bit about mock if you haven't yet. It's pretty useful.

Question 8
What does this stuff mean: *args, **kwargs? And why would we use it?

Answer

Use *args when we aren't sure how many arguments are going to be passed to a function, or if
we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we dont
know how many keyword arguments will be passed to a function, or it can be used to pass the
values of a dictionary as keyword arguments. The identifiers args and kwargs are a convention,
you could also use *bob and **billy but that would not be wise.

Here is a little illustration:

def f(*args,**kwargs): print(args, kwargs)

l = [1,2,3]
t = (4,5,6)
d = {'a':7,'b':8,'c':9}

f()
f(1,2,3) # (1, 2, 3) {}
f(1,2,3,"groovy") # (1, 2, 3, 'groovy') {}
f(a=1,b=2,c=3) # () {'a': 1, 'c': 3, 'b': 2}
f(a=1,b=2,c=3,zzz="hi") # () {'a': 1, 'c': 3, 'b': 2, 'zzz': 'hi'}
f(1,2,3,a=1,b=2,c=3) # (1, 2, 3) {'a': 1, 'c': 3, 'b': 2}

f(*l,**d) # (1, 2, 3) {'a': 7, 'c': 9, 'b': 8}


f(*t,**d) # (4, 5, 6) {'a': 7, 'c': 9, 'b': 8}
f(1,2,*t) # (1, 2, 4, 5, 6) {}
f(q="winning",**d) # () {'a': 7, 'q': 'winning', 'c': 9, 'b': 8}
f(1,2,*t,q="winning",**d) # (1, 2, 4, 5, 6) {'a': 7, 'q': 'winning', 'c': 9,
'b': 8}

def f2(arg1,arg2,*args,**kwargs): print(arg1,arg2, args, kwargs)

f2(1,2,3) # 1 2 (3,) {}
f2(1,2,3,"groovy") # 1 2 (3, 'groovy') {}
f2(arg1=1,arg2=2,c=3) # 1 2 () {'c': 3}
f2(arg1=1,arg2=2,c=3,zzz="hi") # 1 2 () {'c': 3, 'zzz': 'hi'}
f2(1,2,3,a=1,b=2,c=3) # 1 2 (3,) {'a': 1, 'c': 3, 'b': 2}

f2(*l,**d) # 1 2 (3,) {'a': 7, 'c': 9, 'b': 8}


f2(*t,**d) # 4 5 (6,) {'a': 7, 'c': 9, 'b': 8}
f2(1,2,*t) # 1 2 (4, 5, 6) {}
f2(1,1,q="winning",**d) # 1 1 () {'a': 7, 'q': 'winning', 'c': 9, 'b': 8}
f2(1,2,*t,q="winning",**d) # 1 2 (4, 5, 6) {'a': 7, 'q': 'winning', 'c': 9,
'b': 8}

Why Care?

Sometimes we will need to pass an unknown number of arguments or keyword arguments into a
function. Sometimes we will want to store arguments or keyword arguments for later use.
Sometimes it's just a time saver.

Question 9
What do these mean to you: @classmethod, @staticmethod, @property?

Answer Background Knowledge

These are decorators. A decorator is a special kind of function that either takes a function and
returns a function, or takes a class and returns a class. The @ symbol is just syntactic sugar that
allows you to decorate something in a way that's easy to read.

@my_decorator
def my_func(stuff):
do_things

Is equivalent to

def my_func(stuff):
do_things

my_func = my_decorator(my_func)
You can find a tutorial on how decorators in general work here.

Actual Answer

The decorators @classmethod, @staticmethod and @property are used on functions defined
within classes. Here is how they behave:

class MyClass(object):
def __init__(self):
self._some_property = "properties are nice"
self._some_other_property = "VERY nice"
def normal_method(*args,**kwargs):
print("calling normal_method({0},{1})".format(args,kwargs))
@classmethod
def class_method(*args,**kwargs):
print("calling class_method({0},{1})".format(args,kwargs))
@staticmethod
def static_method(*args,**kwargs):
print("calling static_method({0},{1})".format(args,kwargs))
@property
def some_property(self,*args,**kwargs):
print("calling some_property getter({0},{1},
{2})".format(self,args,kwargs))
return self._some_property
@some_property.setter
def some_property(self,*args,**kwargs):
print("calling some_property setter({0},{1},
{2})".format(self,args,kwargs))
self._some_property = args[0]
@property
def some_other_property(self,*args,**kwargs):
print("calling some_other_property getter({0},{1},
{2})".format(self,args,kwargs))
return self._some_other_property

o = MyClass()
# undecorated methods work like normal, they get the current instance (self)
as the first argument

o.normal_method
# <bound method MyClass.normal_method of <__main__.MyClass instance at
0x7fdd2537ea28>>

o.normal_method()
# normal_method((<__main__.MyClass instance at 0x7fdd2537ea28>,),{})

o.normal_method(1,2,x=3,y=4)
# normal_method((<__main__.MyClass instance at 0x7fdd2537ea28>, 1, 2),{'y': 4,
'x': 3})

# class methods always get the class as the first argument

o.class_method
# <bound method classobj.class_method of <class __main__.MyClass at
0x7fdd2536a390>>
o.class_method()
# class_method((<class __main__.MyClass at 0x7fdd2536a390>,),{})

o.class_method(1,2,x=3,y=4)
# class_method((<class __main__.MyClass at 0x7fdd2536a390>, 1, 2),{'y': 4,
'x': 3})

# static methods have no arguments except the ones you pass in when you call
them

o.static_method
# <function static_method at 0x7fdd25375848>

o.static_method()
# static_method((),{})

o.static_method(1,2,x=3,y=4)
# static_method((1, 2),{'y': 4, 'x': 3})

# properties are a way of implementing getters and setters. It's an error to


explicitly call them
# "read only" attributes can be specified by creating a getter without a
setter (as in some_other_property)

o.some_property
# calling some_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,
(),{})
# 'properties are nice'

o.some_property()
# calling some_property getter(<__main__.MyClass instance at 0x7fb2b70877e8>,
(),{})
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: 'str' object is not callable

o.some_other_property
# calling some_other_property getter(<__main__.MyClass instance at
0x7fb2b70877e8>,(),{})
# 'VERY nice'

# o.some_other_property()
# calling some_other_property getter(<__main__.MyClass instance at
0x7fb2b70877e8>,(),{})
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: 'str' object is not callable

o.some_property = "groovy"
# calling some_property setter(<__main__.MyClass object at 0x7fb2b7077890>,
('groovy',),{})

o.some_property
# calling some_property getter(<__main__.MyClass object at 0x7fb2b7077890>,(),
{})
# 'groovy'
o.some_other_property = "very groovy"
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# AttributeError: can't set attribute

o.some_other_property
# calling some_other_property getter(<__main__.MyClass object at
0x7fb2b7077890>,(),{})
# 'VERY nice'

Question 10
Consider the following code, what will it output?

class A(object):
def go(self):
print("go A go!")
def stop(self):
print("stop A stop!")
def pause(self):
raise Exception("Not Implemented")

class B(A):
def go(self):
super(B, self).go()
print("go B go!")

class C(A):
def go(self):
super(C, self).go()
print("go C go!")
def stop(self):
super(C, self).stop()
print("stop C stop!")

class D(B,C):
def go(self):
super(D, self).go()
print("go D go!")
def stop(self):
super(D, self).stop()
print("stop D stop!")
def pause(self):
print("wait D wait!")

class E(B,C): pass

a = A()
b = B()
c = C()
d = D()
e = E()

# specify output from here onwards


a.go()
b.go()
c.go()
d.go()
e.go()

a.stop()
b.stop()
c.stop()
d.stop()
e.stop()

a.pause()
b.pause()
c.pause()
d.pause()
e.pause()

Answer

The output is specified in the comments in the segment below:

a.go()
# go A go!

b.go()
# go A go!
# go B go!

c.go()
# go A go!
# go C go!

d.go()
# go A go!
# go C go!
# go B go!
# go D go!

e.go()
# go A go!
# go C go!
# go B go!

a.stop()
# stop A stop!

b.stop()
# stop A stop!

c.stop()
# stop A stop!
# stop C stop!
d.stop()
# stop A stop!
# stop C stop!
# stop D stop!

e.stop()
# stop A stop!

a.pause()
# ... Exception: Not Implemented

b.pause()
# ... Exception: Not Implemented

c.pause()
# ... Exception: Not Implemented

d.pause()
# wait D wait!

e.pause()
# ...Exception: Not Implemented

Why do we care?

Because OO programming is really, really important. Really. Answering this question shows
your understanding of inheritance and the use of Python's super function. Most of the time the
order of resolution doesn't matter. Sometimes it does, it depends on your application.

Question 11
Consider the following code, what will it output?

class Node(object):
def __init__(self,sName):
self._lChildren = []
self.sName = sName
def __repr__(self):
return "<Node '{}'>".format(self.sName)
def append(self,*args,**kwargs):
self._lChildren.append(*args,**kwargs)
def print_all_1(self):
print(self)
for oChild in self._lChildren:
oChild.print_all_1()
def print_all_2(self):
def gen(o):
lAll = [o,]
while lAll:
oNext = lAll.pop(0)
lAll.extend(oNext._lChildren)
yield oNext
for oNode in gen(self):
print(oNode)

oRoot = Node("root")
oChild1 = Node("child1")
oChild2 = Node("child2")
oChild3 = Node("child3")
oChild4 = Node("child4")
oChild5 = Node("child5")
oChild6 = Node("child6")
oChild7 = Node("child7")
oChild8 = Node("child8")
oChild9 = Node("child9")
oChild10 = Node("child10")

oRoot.append(oChild1)
oRoot.append(oChild2)
oRoot.append(oChild3)
oChild1.append(oChild4)
oChild1.append(oChild5)
oChild2.append(oChild6)
oChild4.append(oChild7)
oChild3.append(oChild8)
oChild3.append(oChild9)
oChild6.append(oChild10)

# specify output from here onwards

oRoot.print_all_1()
oRoot.print_all_2()

Answer

oRoot.print_all_1() prints:

<Node 'root'>
<Node 'child1'>
<Node 'child4'>
<Node 'child7'>
<Node 'child5'>
<Node 'child2'>
<Node 'child6'>
<Node 'child10'>
<Node 'child3'>
<Node 'child8'>
<Node 'child9'>

oRoot.print_all_2() prints:

<Node 'root'>
<Node 'child1'>
<Node 'child2'>
<Node 'child3'>
<Node 'child4'>
<Node 'child5'>
<Node 'child6'>
<Node 'child8'>
<Node 'child9'>
<Node 'child7'>
<Node 'child10'>

Why do we care?

Because composition and object construction is what objects are all about. Objects are composed
of stuff and they need to be initialised somehow. This also ties up some stuff about recursion and
use of generators.

Generators are great. You could have achieved similar functionality to print_all_2 by just
constructing a big long list and then printing it's contents. One of the nice things about generators
is that they don't need to take up much space in memory.

It is also worth pointing out that print_all_1 traverses the tree in a depth-first manner, while
print_all_2 is width-first. Make sure you understand those terms. Sometimes one kind of
traversal is more appropriate than the other. But that depends very much on your application.

Question 12
Describe Python's garbage collection mechanism in brief.

Answer

A lot can be said here. There are a few main points that you should mention:

Python maintains a count of the number of references to each object in memory. If a


reference count goes to zero then the associated object is no longer live and the memory
allocated to that object can be freed up for something else

occasionally things called "reference cycles" happen. The garbage collector periodically
looks for these and cleans them up. An example would be if you have two objects o1 and
o2 such that o1.x == o2 and o2.x == o1. If o1 and o2 are not referenced by anything
else then they shouldn't be live. But each of them has a reference count of 1.

Certain heuristics are used to speed up garbage collection. For example, recently created
objects are more likely to be dead. As objects are created, the garbage collector assigns
them to generations. Each object gets one generation, and younger generations are dealt
with first.

This explanation is CPython specific.

Question 13
Place the following functions below in order of their efficiency. They all take in a list of numbers
between 0 and 1. The list can be quite long. An example input list would be [random.random()
for i in range(100000)]. How would you prove that your answer is correct?

def f1(lIn):
l1 = sorted(lIn)
l2 = [i for i in l1 if i<0.5]
return [i*i for i in l2]

def f2(lIn):
l1 = [i for i in lIn if i<0.5]
l2 = sorted(l1)
return [i*i for i in l2]

def f3(lIn):
l1 = [i*i for i in lIn]
l2 = sorted(l1)
return [i for i in l1 if i<(0.5*0.5)]

Answer

Most to least efficient: f2, f1, f3. To prove that this is the case, you would want to profile your
code. Python has a lovely profiling package that should do the trick.

import cProfile
lIn = [random.random() for i in range(100000)]
cProfile.run('f1(lIn)')
cProfile.run('f2(lIn)')
cProfile.run('f3(lIn)')

For completion's sake, here is what the above profile outputs:

>>> cProfile.run('f1(lIn)')
4 function calls in 0.045 seconds

Ordered by: standard name

ncalls tottime percall cumtime percall filename:lineno(function)


1 0.009 0.009 0.044 0.044 <stdin>:1(f1)
1 0.001 0.001 0.045 0.045 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of
'_lsprof.Profiler' objects}
1 0.035 0.035 0.035 0.035 {sorted}

>>> cProfile.run('f2(lIn)')
4 function calls in 0.024 seconds

Ordered by: standard name

ncalls tottime percall cumtime percall filename:lineno(function)


1 0.008 0.008 0.023 0.023 <stdin>:1(f2)
1 0.001 0.001 0.024 0.024 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of
'_lsprof.Profiler' objects}
1 0.016 0.016 0.016 0.016 {sorted}

>>> cProfile.run('f3(lIn)')
4 function calls in 0.055 seconds

Ordered by: standard name

ncalls tottime percall cumtime percall filename:lineno(function)


1 0.016 0.016 0.054 0.054 <stdin>:1(f3)
1 0.001 0.001 0.055 0.055 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of
'_lsprof.Profiler' objects}
1 0.038 0.038 0.038 0.038 {sorted}

Why Care?

Locating and avoiding bottlenecks is often pretty worthwhile. A lot of coding for efficiency
comes down to common sense - in the example above it's obviously quicker to sort a list if it's a
smaller list, so if you have the choice of filtering before a sort it's often a good idea. The less
obvious stuff can still be located through use of the proper tools. It's good to know about these
tools.

Question 14
Something you failed at?

Wrong answer

I never fail!

Why This Is Important:

Shows that you are capable of admitting errors, taking responsibility for your mistakes, and
learning from your mistakes. All of these things are pretty darn important if you are going to be
useful. If you are actually perfect then too bad, you might need to get creative here.

Question 15
Do you have any personal projects?

Really?

This shows that you are willing to do more than the bare minimum in terms of keeping your
skillset up to date. If you work on personal projects and code outside of the workplace then
employers are more likely to see you as an asset that will grow. Even if they don't ask this
question I find it's useful to broach the subject.

Conclusion
These questions intentionally touched on many topics. And the answers were intentionally
verbose. In a programming interview, you will need to demonstrate your understanding and if
you can do it in a concise way then by all means do that. I tried to give enough information in the
answers that you could glean some meaning from them even if you had never heard of some of
these topics before. I hope you find this useful in your job hunt.

Go get 'em tiger.

1. Compare Java & Python


Criteria Java Python
Ease of use Good Very Good
Speed of coding Average Excellent
Data types Static typed Dynamically typed
Data Science & machine learning applications Average Very Good
2. How are the functions help() and dir() different?

These are the two functions that are accessible from the Python Interpreter. These two functions
are used for viewing a consolidated dump of built-in functions.

help() it will display the documentation string. It is used to see the help related to
modules, keywords, attributes, etc.
To view the help related to string datatype, just execute a statement help(str) it will
display the documentation for str, module. Eg: >>>help(str) or >>>help() it will open
the prompt for help as help>

to view the help for a module, help> module module name Inorder to view the
documentation of str at the help>, type help>modules str

to view the help for a keyword, topics, you just need to type, help> keywords python-
keyword and topics list

dir() will display the defined symbols. Eg: >>>dir(str) will only display the defined
symbols.

Go through this Python tutorial to learn more about Python Functions.

3. Which command do you use to exit help window or help command prompt?
quit
When you type quit at the helps command prompt, python shell prompt will appear by closing
the help window automatically.

Check this insightful tutorial to learn more about Python Program & its Execution.

Get Python Certification in just 16 Hours

GET CERTIFIED
4. Does the functions help() and dir() list the names of all the built_in functions and variables? If
no, how would you list them?

No. Built-in functions such as max(), min(), filter(), map(), etc is not apparent immediately as
they are
available as part of standard module.To view them, we can pass the module builtins as an
argument to dir(). It will display the
built-in functions, exceptions, and other objects as a list.>>>dir(__builtins )
[ArithmeticError, AssertionError, AttributeError, ]

5. Explain how Python does Compile-time and Run-time code checking?

Python performs some amount of compile-time checking, but most of the checks such as type,
name, etc are postponed until code execution. Consequently, if the Python code references a user
-defined function that does not exist, the code will compile successfully. In fact, the code will fail
with an exception only when the code execution path references the function which does not
exists.

Read this blog to learn how to deploy automated coding with Python.

6. Whenever Python exists Why does all the memory is not de-allocated / freed when Python
exits?

Whenever Python exits, especially those python modules which are having circular references to
other objects or the objects that are referenced from the global namespaces are not always de
allocated/freed/uncollectable.
It is impossible to deallocate those portions of memory that are reserved by the C library.
On exit, because of having its own efficient clean up mechanism, Python would try to deallocate/
destroy every object.

Want to Learn python? Click Here

7. Explain Python's zip() function.?


zip() function- it will take multiple lists say list1, list2, etc and transform them into a single list of
tuples by taking the corresponding elements of the lists that are passed as parameters. Eg:

list1 = ['A',
'B','C'] and list2 = [10,20,30].
zip(list1, list2) # results in a list of tuples say [('A',10),('B',20),
('C',30)]

whenever the given lists are of different lengths, zip stops generating tuples when the first list
ends.

8. Explain Python's pass by references Vs pass by value . (or) Explain about Python's parameter
passing mechanism?

In Python, by default, all the parameters (arguments) are passed by reference to the functions.
Thus, if you change the value of the parameter within a function, the change is reflected in the
calling function.We can even observe the pass by value kind of a behaviour whenever we pass
the arguments to functions that are of type say numbers, strings, tuples. This is because of the
immutable nature of them.

Learn all about Python through this Python training course.

9. As Everything in Python is an Object, Explain the characteristics of Python's Objects.

As Pythons Objects are instances of classes, they are created at the time of instantiation.
Eg: object-name = class-name(arguments)

one or more variables can reference the same object in Python

Every object holds unique id and it can be obtained by using id() method. Eg: id(obj-
name) will return unique id of the given object.
every object can be either mutable or immutable based on the type of data they hold.

Whenever an object is not being used in the code, it gets destroyed automatically
garbage collected or destroyed

contents of objects can be converted into string representation using a method

Go through this Python Video to get clear understanding of Python.

Download Python Interview questions asked by top MNCs in 2017 ?

10. Explain how to overload constructors or methods in Python.


Pythons constructor _init__ () is a first method of a class. Whenever we try to instantiate a
object __init__() is automatically invoked by python to initialize members of an object.

11. Which statement of Python is used whenever a statement is required syntactically but the
program needs no action?

Pass is no-operation / action statement in Python


If we want to load a module or open a file, and even if the requested module/file does not exist,
we want to continue with other tasks. In such a scenario, use try-except block with pass
statement in the except block.
Eg:

try:import mymodulemyfile = open(C:\myfile.csv)except:pass


12. What is Web Scraping? How do you achieve it in Python?

Web Scrapping is a way of extracting the large amounts of information which is available on the
web sites and saving it onto the local machine or onto the database tables.
In order to scrap the web:load the web page which is interesting to you. To load the web page,
use requests module.
parse HTML from the web page to find the interesting information.Python has few modules for
scraping the web. They are urllib2, scrapy, pyquery, BeautifulSoap, etc.

Master Python, in this Python certification training.

13. What is a Python module?

A module is a Python script that generally contains import statements, functions, classes and
variable definitions, and Python runnable code and it lives file with a .py extension. zip files
and DLL files can also be modules.Inside the module, you can refer to the module name as a
string that is stored in the global variable name .
A module can be imported by other modules in one of the two ways. They are

1. import

2. from module-name import

Check this tutorial to learn more about Python modules.

14. Name the File-related modules in Python?

Python provides libraries / modules with functions that enable you to manipulate text files and
binary files on file system. Using them you can create files, update their contents, copy, and
delete files. The libraries are : os, os.path, and shutil.
Here, os and os.path modules include functions for accessing the filesystem
shutil module enables you to copy and delete the files.
15. Explain the use of with statement?

In python generally with statement is used to open a file, process the data present in the file,
and also to close the file without calling a close() method. with statement makes the exception
handling simpler by providing cleanup activities.
General form of with:
with open(file name, mode) as file-var:
processing statements
note: no need to close the file by calling close() upon file-var.close()

16. Explain all the file processing modes supported by Python ?

Python allows you to open files in one of the three modes. They are:
read-only mode, write-only mode, read-write mode, and append mode by specifying the flags
r, w, rw, a respectively.
A text file can be opened in any one of the above said modes by specifying the option t along
with
r, w, rw, and a, so that the preceding modes become rt, wt, rwt, and at.A binary
file can be opened in any one of the above said modes by specifying the option b along with
r, w, rw, and a so that the preceding modes become rb, wb, rwb, ab.

17. Explain how to redirect the output of a python script from standout(ie., monitor) on to a file ?

They are two possible ways of redirecting the output from standout to a file.

1. Open an output file in write mode and the print the contents in to that file, using
sys.stdout attribute.
import sys
filename = outputfile sys.stdout = open() print testing

2. you can create a python script say .py file with the contents, say print testing and then
redirect it to the output file while executing it at the command prompt.
Eg: redirect_output.py has the following code:
print Testing
execution: python redirect_output.py > outputfile.

Go through this Python tutorial to get better understanding of Python Input & Output.

18. Explain the shortest way to open a text file and display its contents.?

The shortest way to open a text file is by using with command as follows:

with open("file-name", "r") as fp:


fileData = fp.read()
#to print the contents of the file print(fileData)
19. How do you create a dictionary which can preserve the order of pairs?
We know that regular Python dictionaries iterate over <key, value> pairs in an arbitrary order,
hence they do not preserve the insertion order of <key, value> pairs.
Python 2.7. introduced a new OrderDict class in the collections module and it provides the
same interface like the general dictionaries but it traverse through keys and values in an ordered
manner depending on when a key was first inserted.
Eg:

from collections import OrderedDict


d = OrderDict([('Company-id':1),('Company-Name':'Intellipaat')])
d.items() # displays the output as: [('Company-id':1),('Company-
Name':'Intellipaat')]
20. When does a dictionary is used instead of a list?

Dictionaries are best suited when the data is labelled, i.e., the data is a record with field names.
lists are better option to store collections of un-labelled items say all the files and sub
directories in a folder.
Generally Search operation on dictionary object is faster than searching a list object.

Read this tutorial to learn more about Python Dictionary.

21. What is the use of enumerate() in Python?

Using enumerate() function you can iterate through the sequence and retrieve the index position
and its corresponding value at the same time.
>>> for i,v in enumerate([Python,Java,C++]):
print(i,v)
0 Python
1 Java
2 C++

22. How many kinds of sequences are supported by Python? What are they?

Python supports 7 sequence types. They are str, list, tuple, unicode, bytearray, xrange, and buffer.
where xrange is deprecated in python 3.5.X.

23. How do you perform pattern matching in Python? Explain

Regular Expressions/REs/ regexes enable us to specify expressions that can match specific
parts of a given string. For instance, we can define a regular expression to match a single
character or a digit, a telephone number, or an email address, etc.The Pythons re module
provides regular expression patterns and was introduce from later versions of Python 2.5. re
module is providing methods for search text strings, or replacing text strings along with methods
for splitting text strings based on the pattern defined.

24. Name few methods for matching and searching the occurrences of a pattern in a given text
String ?
There are 4 different methods in re module to perform pattern matching. They are:
match() matches the pattern only to the beginning of the String. search() scan the string and
look for a location the pattern matches findall() finds all the occurrences of match and return
them as a list
finditer() finds all the occurrences of match and return them as an iterator.

25. Explain split(), sub(), subn() methods of

To modify the strings, Pythons re module is providing 3 methods. They are:


split() uses a regex pattern to split a given string into a list.
sub() finds all substrings where the regex pattern matches and then replace them with a
different string
subn() it is similar to sub() and also returns the new string along with the no. of
replacements.

26. How to display the contents of text file in reverse order?

1. convert the given file into a list.

2. reverse the list by using reversed()


Eg: for line in reversed(list(open(file-name,r))):
print(line)

27. What is JSON? How would convert JSON data into Python data?

JSON stands for JavaScript Object Notation. It is a popular data format for storing data in
NoSQL
databases. Generally JSON is built on 2 structures.

1. A collection of <name, value> pairs.

2. An ordered list of values.


As Python supports JSON parsers, JSON-based data is actually represented as a
dictionary in Python. You can convert json data into python using load() of json module.

28. Name few Python modules for Statistical, Numerical and scientific computations ?

numPy this module provides an array/matrix type, and it is useful for doing computations on
arrays. scipy this module provides methods for doing numeric integrals, solving differential
equations, etc pylab is a module for generating and saving plots
matplotlib used for managing data and generating plots.

29. What is TkInter?


TkInter is Python library. It is a toolkit for GUI development. It provides support for various GUI
tools or widgets (such as buttons, labels, text boxes, radio buttons, etc) that are used in GUI
applications. The common attributes of them include Dimensions, Colors, Fonts, Cursors, etc.

30. Name and explain the three magic methods of Python that are used in the construction and
initialization of custom Objects.

The 3 magic methods of Python that are used in the construction and initialization of custom
Objects are: init__, new , and del__.
new this method can be considered as a constructor. It is invoked to create an instance of a
class with the statement say, myObj = MyClass()
init__ It is an initializer/ constructor method. It is invoked whenever any arguments are
passed at the time of creating an object. myObj = MyClass(Pizza,25)
del- this method is a destructor of the class. Whenever an object is deleted,
invocation of del__ takes place and it defines behaviour during the garbage collection. Note: new
, del are rarely used explicitly.

31. Is Python object oriented? what is object oriented programming?

Yes. Python is Object Oriented Programming language. OOP is the programming paradigm
based on classes and instances of those classes called objects. The features of OOP are:
Encapsulation, Data Abstraction, Inheritance, Polymorphism.

32. What is a Class? How do you create it in Python?

A class is a blue print/ template of code /collection of objects that has same set of attributes and
behaviour. To create a class use the keyword class followed by class name beginning with an
uppercase letter. For example, a person belongs to class called Person class and can have the
attributes (say first-name and last-name) and behaviours / methods (say showFullName()). A
Person class can be defined as:

class Person():
#method
def inputName(self,fname,lname): self.fname=fname self.lastname=lastname
#method
def showFullName() (self):
print(self.fname+" "+self.lname)person1 = Person() #object instantiation
person1.inputName("Ratan","Tata") #calling a method inputName person1.
showFullName() #calling a method showFullName()

Note: whenever you define a method inside a class, the first argument to the method must be self
(where self is a pointer to the class instance). self must be passed as an argument to the method,
though the method does not take any arguments.

33. What are Exception Handling? How do you achieve it in Python?

Exception Handling prevents the codes and scripts from breaking on receipt of an error at run
-time might be at the time doing I/O, due to syntax errors, data types doesnt match. Generally it
can be used for handling user inputs.
The keywords that are used to handle exceptions in Python are:
try it will try to execute the code that belongs to it. May be it used anywhere that keyboard
input is required.
except catches all errors or can catch a specific error. It is used after the try block.x = 10 +
Python #TypeError: unsupported operand type(s) . try:
x = 10 + Python
except:
print(incompatible operand types to perform sum)
raise force an error to occur
o raise TypeError(dissimilar data types)
finally it is an optional clause and in this block cleanup code is written here following try and
except.

34. Explain Inheritance in Python with an example.

Inheritance allows One class to gain all the members(say attributes and methods) of another
class. Inheritance provides code reusability, makes it easier to create and maintain an application.
They are different types of inheritance supported by Python. They are: single, multi-level,
hierarchical and multiple inheritance. The class from which we are inheriting is called super-
class and the class that is inherited is called a derived / child class.
Single Inheritance where a derived class acquires the members of a single super class.
multi-level inheritance a derived class d1 in inherited from base class base1, and d2 is inherited
from base2.
hierarchical inheritance from one base class you can inherit any number of child classes
multiple inheritance a derived class is inherited from more than one base class.
ex:

class ParentClass:
v1 = "from ParentClass - v1"
v2 = "from ParentClass - v2"class ChildClass(ParentClass):
passc = ChildClass() print(c.v1) print(c.v2)
35. What is multithreading? Give an example.

It means running several different programs at the same time concurrently by invoking multiple
threads. Multiple threads within a process refer the data space with main thread and they can
communicate with each other to share information more easily.Threads are light-weight
processes and have less memory overhead. Threads can be used just for quick task like
calculating results and also running other processes in the background while the main program is
running.

36. How instance variables are different from class variables?

Instance variables: are the variables in an object that have values that are local to that object.
Two objects of the same class maintain distinct values for their variables. These variables are
accessed with object-name.instancevariable-name.
class variables: these are the variables of class. All the objects of the same class will share value
of Class variables. They are accessed with their class name alone as class- name.classvariable-
name. If you change the value of a class variable in one object, its new value is visible among
all other objects of the same class. In the Java world, a variable that is declared as static is a class
variable.

37. Explain different ways to trigger / raise exceptions in your python script ?

The following are the two possible ways by which you can trigger an exception in your Python
script. They are:

1. raise it is used to manually raise an exception general-form:


raise exception-name (message to be conveyed)
Eg: >>> voting_age = 15
>>> if voting_age < 18: raise ValueError(voting age should be atleast 18 and above)
output: ValueError: voting age should be atleast 18 and above 2. assert statement assert
statements are used to tell your program to test that condition attached to assert keyword,
and trigger an exception whenever the condition becomes false. Eg: >>> a = -10
>>> assert a > 0 #to raise an exception whenever a is a negative number output:
AssertionError
Another way of raising and exception can be done by making a programming mistake,
but thats not
usually a good way of triggering an exception.

38. How is Inheritance and Overriding methods are related?

If class A is a sub class of class B, then everything in B is accessible in /by class A. In addition,
class A can define methods that are unavailable in B, and also it is able to override methods in B.
For Instance, If class B and class A both contain a method called func(), then func() in class B
can override func() in class A. Similarly, a method of class A can call another method defined in
A that can invoke a method of B that overrides it.

39. Which methods of Python are used to determine the type of instance and inheritance?

Python has 2 built-in functions that work with inheritance:


isinstance() this method checks the type of instance.

for eg, isinstance(myObj, int) returns True only when myObj. class is int.
issubclass() this method checks class inheritance

for eg: issubclass(bool, int) returns True because bool is a subclass of int.

issubclass(unicode, str) returns False because unicode is not a subclass of str.

40. In the case of Multiple inheritance, if a child class C is derived from two base classes say A
and B as: class C(A, B): -- which parent class's method will be invoked by the interpreter
whenever object of class C calls a method func() that is existing in both the parent classes say A
and B and does not exist in class C as

since class C does not contain the definition of the method func(), they Python searches for the
func() in parent classes. Since the search is performed in a left-to-right fashion, Python executes
the method func() present in class A and not the func() method in B.

41. Does Python supports interfaces like in Java? Discuss.

Python does not provide interfaces like in Java. Abstract Base Class (ABC) and its feature are
provided by the Pythons abc module. Abstract Base Class is a mechanism for specifying what
methods must be implemented by its implementation subclasses. The use of ABCc provides a
sort of understanding about methods and their expected behaviour. This module was made
available from Python 2.7 version onwards.

42. What are Accessors, mutators, @property?

Accessors and mutators are often called getters and setters in languages like Java. For
example, if x is a property of a user-defined class, then the class would have methods called
setX() and getX(). Python has an @property decorator that allows you to ad getters and setters
in order to access the attribute of the class.

43. Differentiate between .py and .pyc files?

Both .py and .pyc files holds the byte code. .pyc is a compiled version of Python file. This file
is automatically generated by Python to improve performance. The .pyc file is having byte code
which is platform independent and can be executed on any operating system that supports .pyc
format.
Note: there is no difference in speed when program is read from .pyc or .py file; the only
difference is the load time.

44. How to retrieve data from a table in MySQL database through Python code? Explain.

1. import MySQLdb module as : import MySQLdb

2. establish a connection to the database.


db = MySQLdb.connect(host=local host, database-user=user-name,
password=password, database-name=database)

3. initialize the cursor variable upon the established connection: c1 = db.cursor()

4. retrieve the information by defining a required query string. s = Select * from dept

5. fetch the data using fetch() methods and print it. data = c1.fetch(s)

6. close the database connection. db.close()


45. Explain about ODBC and Python ?

ODBC (Open Database Connectivity) API standard allows the connections with any database
that supports the interface, such as PostgreSQL database or Microsoft Access in a transparent
manner . There are 3 ODBC modules for Python:

1. PythonWin ODBC module limited development

2. mxODBC commercial product

3. pyodbc it is an open source Python package.

46. How would you define a protected member in a Python class?

All the members of a class in Python are public by default. You dont need to define an access
specifier for members of class. By adding _ as a prefix to the member of a class, by convetion
you are telling others please dont this object, if you are not a subclass the respective class.
Eg: class Person:
empid = None
_salary = None #salary is a protected member & it can accessible by the subclasses of Person
.

47. How do you remove duplicates from a list?

a. sort the list


b. scan the list from the end.
c. while scanning from right-to-left, delete all the duplicate elements from the list

48. Differentiate between append() and extend() methods. ?

Both append() and extend() methods are the methods of list. These methods a re used to add the
elements at the end of the list.
append(element) adds the given element at the end of the list which has called this method.
extend(another-list) adds the elements of another-list at the end of the list which is called the
extend method.

49. Name few Python Web Frameworks for developing web applications?

There are various web frameworks provided by Python. They are


web2py it is the simplest of all the web frameworks used for developing web applications.
cherryPy it is a Python-based Object oriented Web framework.
Flask it is a Python-based micro-framework for designing and developing web applications.

50. How do you check the file existence and their types in Python?
os.path.exists() use this method to check for the existence of a file. It returns True if the file
exists, false otherwise. Eg: import os; os.path.exists(/etc/hosts)
os.path.isfile() this method is used to check whether the give path references a file or not. It
returns True if the path references to a file, else it returns false. Eg: import os;
os.path.isfile(/etc/hosts)
os.path.isdir() this method is used to check whether the give path references a directory or not.
It returns True if the path references to a directory, else it returns false. Eg: import os;
os.path.isfile(/etc/hosts)
os.path.getsize() returns the size of the given file
os.path.getmtime() returns the timestamp of the given path.

51. Name few methods that are used to implement Functionally Oriented Programming in
Python?

Python supports methods (called iterators in Python3), such as filter(), map(), and reduce(), that
are very useful when you need to iterate over the items in a list, create a dictionary, or extract a
subset of a list.
filter() enables you to extract a subset of values based on conditional logic.
map() it is a built-in function that applies the function to each item in an iterable.
reduce() repeatedly performs a pair-wise reduction on a sequence until a single value is
computed.

100+ Python challenging programming exercises

1. Level description

Level Description

Level 1 Beginner means someone who has just gone through an introductory Python course. He
can solve some problems with 1 or 2 Python classes or functions. Normally, the answers could
directly be found in the textbooks.

Level 2 Intermediate means someone who has just learned Python, but already has a relatively
strong programming background from before. He should be able to solve problems which may
involve 3 or 3 Python classes or functions. The answers cannot be directly be found in the
textbooks.

Level 3 Advanced. He should use Python to solve more complex problem using more rich
libraries functions and data structures and algorithms. He is supposed to solve the problem using
several Python standard packages and advanced techniques.
2. Problem template

#----------------------------------------#

Question

Hints

Solution

3. Questions

#----------------------------------------#

Question 1

Level 1

Question:

Write a program which will find all such numbers which are divisible by 7 but are not a multiple
of 5,

between 2000 and 3200 (both included).

The numbers obtained should be printed in a comma-separated sequence on a single line.

Hints:

Consider use range(#begin, #end) method


Solution:

l=[]

for i in range(2000, 3201):

if (i%7==0) and (i%5!=0):

l.append(str(i))

print ','.join(l)

#----------------------------------------#

#----------------------------------------#

Question 2

Level 1

Question:

Write a program which can compute the factorial of a given numbers.

The results should be printed in a comma-separated sequence on a single line.

Suppose the following input is supplied to the program:

Then, the output should be:

40320
Hints:

In case of input data being supplied to the question, it should be assumed to be a console input.

Solution:

def fact(x):

if x == 0:

return 1

return x * fact(x - 1)

x=int(raw_input())

print fact(x)

#----------------------------------------#

#----------------------------------------#

Question 3

Level 1

Question:

With a given integral number n, write a program to generate a dictionary that contains (i, i*i)
such that is an integral number between 1 and n (both included). and then the program should
print the dictionary.
Suppose the following input is supplied to the program:

Then, the output should be:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}

Hints:

In case of input data being supplied to the question, it should be assumed to be a console input.

Consider use dict()

Solution:

n=int(raw_input())

d=dict()

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

d[i]=i*i

print d

#----------------------------------------#

#----------------------------------------#

Question 4

Level 1
Question:

Write a program which accepts a sequence of comma-separated numbers from console and
generate a list and a tuple which contains every number.

Suppose the following input is supplied to the program:

34,67,55,33,12,98

Then, the output should be:

['34', '67', '55', '33', '12', '98']

('34', '67', '55', '33', '12', '98')

Hints:

In case of input data being supplied to the question, it should be assumed to be a console input.

tuple() method can convert list to tuple

Solution:

values=raw_input()

l=values.split(",")

t=tuple(l)

print l

print t

#----------------------------------------#
#----------------------------------------#

Question 5

Level 1

Question:

Define a class which has at least two methods:

getString: to get a string from console input

printString: to print the string in upper case.

Also please include simple test function to test the class methods.

Hints:

Use __init__ method to construct some parameters

Solution:

class InputOutString(object):

def __init__(self):

self.s = ""

def getString(self):

self.s = raw_input()

def printString(self):
print self.s.upper()

strObj = InputOutString()

strObj.getString()

strObj.printString()

#----------------------------------------#

#----------------------------------------#

Question 6

Level 2

Question:

Write a program that calculates and prints the value according to the given formula:

Q = Square root of [(2 * C * D)/H]

Following are the fixed values of C and H:

C is 50. H is 30.

D is the variable whose values should be input to your program in a comma-separated sequence.

Example

Let us assume the following comma separated input sequence is given to the program:

100,150,180

The output of the program should be:


18,22,24

Hints:

If the output received is in decimal form, it should be rounded off to its nearest value (for
example, if the output received is 26.0, it should be printed as 26)

In case of input data being supplied to the question, it should be assumed to be a console input.

Solution:

#!/usr/bin/env python

import math

c=50

h=30

value = []

items=[x for x in raw_input().split(',')]

for d in items:

value.append(str(int(round(math.sqrt(2*c*float(d)/h)))))

print ','.join(value)

#----------------------------------------#

#----------------------------------------#

Question 7
Level 2

Question:

Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The
element value in the i-th row and j-th column of the array should be i*j.

Note: i=0,1.., X-1; j=0,1,Y-1.

Example

Suppose the following inputs are given to the program:

3,5

Then, the output of the program should be:

[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]

Hints:

Note: In case of input data being supplied to the question, it should be assumed to be a console
input in a comma-separated form.

Solution:

input_str = raw_input()

dimensions=[int(x) for x in input_str.split(',')]

rowNum=dimensions[0]

colNum=dimensions[1]

multilist = [[0 for col in range(colNum)] for row in range(rowNum)]


for row in range(rowNum):

for col in range(colNum):

multilist[row][col]= row*col

print multilist

#----------------------------------------#

#----------------------------------------#

Question 8

Level 2

Question:

Write a program that accepts a comma separated sequence of words as input and prints the
words in a comma-separated sequence after sorting them alphabetically.

Suppose the following input is supplied to the program:

without,hello,bag,world

Then, the output should be:

bag,hello,without,world

Hints:

In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:

items=[x for x in raw_input().split(',')]

items.sort()

print ','.join(items)

#----------------------------------------#

#----------------------------------------#

Question 9

Level 2

Question

Write a program that accepts sequence of lines as input and prints the lines after making all
characters in the sentence capitalized.

Suppose the following input is supplied to the program:

Hello world

Practice makes perfect

Then, the output should be:

HELLO WORLD

PRACTICE MAKES PERFECT

Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.

Solution:

lines = []

while True:

s = raw_input()

if s:

lines.append(s.upper())

else:

break;

for sentence in lines:

print sentence

#----------------------------------------#

#----------------------------------------#

Question 10

Level 2

Question:

Write a program that accepts a sequence of whitespace separated words as input and prints the
words after removing all duplicate words and sorting them alphanumerically.
Suppose the following input is supplied to the program:

hello world and practice makes perfect and hello world again

Then, the output should be:

again and hello makes perfect practice world

Hints:

In case of input data being supplied to the question, it should be assumed to be a console input.

We use set container to remove duplicated data automatically and then use sorted() to sort the
data.

Solution:

s = raw_input()

words = [word for word in s.split(" ")]

print " ".join(sorted(list(set(words))))

#----------------------------------------#

#----------------------------------------#

Question 11

Level 2

Question:

Write a program which accepts a sequence of comma separated 4 digit binary numbers as its
input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5
are to be printed in a comma separated sequence.

Example:

0100,0011,1010,1001

Then the output should be:

1010

Notes: Assume the data is input by console.

Hints:

In case of input data being supplied to the question, it should be assumed to be a console input.

Solution:

value = []

items=[x for x in raw_input().split(',')]

for p in items:

intp = int(p, 2)

if not intp%5:

value.append(p)

print ','.join(value)

#----------------------------------------#
#----------------------------------------#

Question 12

Level 2

Question:

Write a program, which will find all such numbers between 1000 and 3000 (both included) such
that each digit of the number is an even number.

The numbers obtained should be printed in a comma-separated sequence on a single line.

Hints:

In case of input data being supplied to the question, it should be assumed to be a console input.

Solution:

values = []

for i in range(1000, 3001):

s = str(i)

if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0):

values.append(s)

print ",".join(values)

#----------------------------------------#

#----------------------------------------#
Question 13

Level 2

Question:

Write a program that accepts a sentence and calculate the number of letters and digits.

Suppose the following input is supplied to the program:

hello world! 123

Then, the output should be:

LETTERS 10

DIGITS 3

Hints:

In case of input data being supplied to the question, it should be assumed to be a console input.

Solution:

s = raw_input()

d={"DIGITS":0, "LETTERS":0}

for c in s:

if c.isdigit():

d["DIGITS"]+=1

elif c.isalpha():
d["LETTERS"]+=1

else:

pass

print "LETTERS", d["LETTERS"]

print "DIGITS", d["DIGITS"]

#----------------------------------------#

#----------------------------------------#

Question 14

Level 2

Question:

Write a program that accepts a sentence and calculate the number of upper case letters and lower
case letters.

Suppose the following input is supplied to the program:

Hello world!

Then, the output should be:

UPPER CASE 1

LOWER CASE 9

Hints:

In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:

s = raw_input()

d={"UPPER CASE":0, "LOWER CASE":0}

for c in s:

if c.isupper():

d["UPPER CASE"]+=1

elif c.islower():

d["LOWER CASE"]+=1

else:

pass

print "UPPER CASE", d["UPPER CASE"]

print "LOWER CASE", d["LOWER CASE"]

#----------------------------------------#

#----------------------------------------#

Question 15

Level 2

Question:

Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.
Suppose the following input is supplied to the program:

Then, the output should be:

11106

Hints:

In case of input data being supplied to the question, it should be assumed to be a console input.

Solution:

a = raw_input()

n1 = int( "%s" % a )

n2 = int( "%s%s" % (a,a) )

n3 = int( "%s%s%s" % (a,a,a) )

n4 = int( "%s%s%s%s" % (a,a,a,a) )

print n1+n2+n3+n4

#----------------------------------------#

#----------------------------------------#

Question 16

Level 2
Question:

Use a list comprehension to square each odd number in a list. The list is input by a sequence of
comma-separated numbers.

Suppose the following input is supplied to the program:

1,2,3,4,5,6,7,8,9

Then, the output should be:

1,3,5,7,9

Hints:

In case of input data being supplied to the question, it should be assumed to be a console input.

Solution:

values = raw_input()

numbers = [x for x in values.split(",") if int(x)%2!=0]

print ",".join(numbers)

#----------------------------------------#

Question 17

Level 2

Question:

Write a program that computes the net amount of a bank account based a transaction log from
console input. The transaction log format is shown as following:

D 100

W 200

D means deposit while W means withdrawal.

Suppose the following input is supplied to the program:

D 300

D 300

W 200

D 100

Then, the output should be:

500

Hints:

In case of input data being supplied to the question, it should be assumed to be a console input.

Solution:

import sys

netAmount = 0

while True:

s = raw_input()
if not s:

break

values = s.split(" ")

operation = values[0]

amount = int(values[1])

if operation=="D":

netAmount+=amount

elif operation=="W":

netAmount-=amount

else:

pass

print netAmount

#----------------------------------------#

#----------------------------------------#

Question 18

Level 3

Question:

A website requires the users to input username and password to register. Write a program to
check the validity of password input by users.

Following are the criteria for checking the password:


1. At least 1 letter between [a-z]

2. At least 1 number between [0-9]

1. At least 1 letter between [A-Z]

3. At least 1 character from [$#@]

4. Minimum length of transaction password: 6

5. Maximum length of transaction password: 12

Your program should accept a sequence of comma separated passwords and will check them
according to the above criteria. Passwords that match the criteria are to be printed, each
separated by a comma.

Example

If the following passwords are given as input to the program:

ABd1234@1,a F1#,2w3E*,2We3345

Then, the output of the program should be:

ABd1234@1

Hints:

In case of input data being supplied to the question, it should be assumed to be a console input.

Solutions:

import re

value = []

items=[x for x in raw_input().split(',')]


for p in items:

if len(p)<6 or len(p)>12:

continue

else:

pass

if not re.search("[a-z]",p):

continue

elif not re.search("[0-9]",p):

continue

elif not re.search("[A-Z]",p):

continue

elif not re.search("[$#@]",p):

continue

elif re.search("\s",p):

continue

else:

pass

value.append(p)

print ",".join(value)

#----------------------------------------#
#----------------------------------------#

Question 19

Level 3

Question:

You are required to write a program to sort the (name, age, height) tuples by ascending order
where name is string, age and height are numbers. The tuples are input by console. The sort
criteria is:

1: Sort based on name;

2: Then sort based on age;

3: Then sort by score.

The priority is that name > age > score.

If the following tuples are given as input to the program:

Tom,19,80

John,20,90

Jony,17,91

Jony,17,93

Json,21,85

Then, the output of the program should be:

[('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]

Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.

We use itemgetter to enable multiple sort keys.

Solutions:

from operator import itemgetter, attrgetter

l = []

while True:

s = raw_input()

if not s:

break

l.append(tuple(s.split(",")))

print sorted(l, key=itemgetter(0,1,2))

#----------------------------------------#

#----------------------------------------#

Question 20

Level 3

Question:

Define a class with a generator which can iterate the numbers, which are divisible by 7, between
a given range 0 and n.

Hints:

Consider use yield

Solution:

def putNumbers(n):

i=0

while i<n:

j=i

i=i+1

if j%7==0:

yield j

for i in reverse(100):

print i

#----------------------------------------#

#----------------------------------------#

Question 21

Level 3
Question

A robot moves in a plane starting from the original point (0,0). The robot can move toward UP,
DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the
following:

UP 5

DOWN 3

LEFT 3

RIGHT 2

The numbers after the direction are steps. Please write a program to compute the distance from
current position after a sequence of movement and original point. If the distance is a float, then
just print the nearest integer.

Example:

If the following tuples are given as input to the program:

UP 5

DOWN 3

LEFT 3

RIGHT 2

Then, the output of the program should be:

Hints:

In case of input data being supplied to the question, it should be assumed to be a console input.
Solution:

import math

pos = [0,0]

while True:

s = raw_input()

if not s:

break

movement = s.split(" ")

direction = movement[0]

steps = int(movement[1])

if direction=="UP":

pos[0]+=steps

elif direction=="DOWN":

pos[0]-=steps

elif direction=="LEFT":

pos[1]-=steps

elif direction=="RIGHT":

pos[1]+=steps

else:

pass
print int(round(math.sqrt(pos[1]**2+pos[0]**2)))

#----------------------------------------#

#----------------------------------------#

Question 22

Level 3

Question:

Write a program to compute the frequency of the words from the input. The output should output
after sorting the key alphanumerically.

Suppose the following input is supplied to the program:

New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.

Then, the output should be:

2:2

3.:1

3?:1

New:1

Python:5

Read:1

and:1
between:1

choosing:1

or:2

to:1

Hints

In case of input data being supplied to the question, it should be assumed to be a console input.

Solution:

freq = {} # frequency of words in text

line = raw_input()

for word in line.split():

freq[word] = freq.get(word,0)+1

words = freq.keys()

words.sort()

for w in words:

print "%s:%d" % (w,freq[w])

#----------------------------------------#

#----------------------------------------#
Question 23

level 1

Question:

Write a method which can calculate square value of number

Hints:

Using the ** operator

Solution:

def square(num):

return num ** 2

print square(2)

print square(3)

#----------------------------------------#

#----------------------------------------#

Question 24

Level 1
Question:

Python has many built-in functions, and if you do not know how to use it, you can read
document online or find some books. But Python has a built-in document function for every
built-in functions.

Please write a program to print some Python built-in functions documents, such as abs(), int(),
raw_input()

And add document for your own function

Hints:

The built-in document method is __doc__

Solution:

print abs.__doc__

print int.__doc__

print raw_input.__doc__

def square(num):

'''Return the square value of the input number.

The input number must be integer.

'''

return num ** 2
print square(2)

print square.__doc__

#----------------------------------------#

#----------------------------------------#

Question 25

Level 1

Question:

Define a class, which have a class parameter and have a same instance parameter.

Hints:

Define a instance parameter, need add it in __init__ method

You can init a object with construct parameter or set the value later

Solution:

class Person:

# Define the class parameter "name"

name = "Person"

def __init__(self, name = None):

# self.name is the instance parameter


self.name = name

jeffrey = Person("Jeffrey")

print "%s name is %s" % (Person.name, jeffrey.name)

nico = Person()

nico.name = "Nico"

print "%s name is %s" % (Person.name, nico.name)

#----------------------------------------#

#----------------------------------------#

Question:

Define a function which can compute the sum of two numbers.

Hints:

Define a function with two numbers as arguments. You can compute the sum in the function and
return the value.

Solution

def SumFunction(number1, number2):

return number1+number2
print SumFunction(1,2)

#----------------------------------------#

Question:

Define a function that can convert a integer into a string and print it in console.

Hints:

Use str() to convert a number to string.

Solution

def printValue(n):

print str(n)

printValue(3)

#----------------------------------------#

Question:

Define a function that can convert a integer into a string and print it in console.
Hints:

Use str() to convert a number to string.

Solution

def printValue(n):

print str(n)

printValue(3)

#----------------------------------------#

2.10

Question:

Define a function that can receive two integral numbers in string form and compute their sum
and then print it in console.

Hints:

Use int() to convert a string to integer.

Solution
def printValue(s1,s2):

print int(s1)+int(s2)

printValue("3","4") #7

#----------------------------------------#

2.10

Question:

Define a function that can accept two strings as input and concatenate them and then print it in
console.

Hints:

Use + to concatenate the strings

Solution

def printValue(s1,s2):

print s1+s2
printValue("3","4") #34

#----------------------------------------#

2.10

Question:

Define a function that can accept two strings as input and print the string with maximum length
in console. If two strings have the same length, then the function should print al l strings line by
line.

Hints:

Use len() function to get the length of a string

Solution

def printValue(s1,s2):

len1 = len(s1)

len2 = len(s2)

if len1>len2:

print s1

elif len2>len1:

print s2
else:

print s1

print s2

printValue("one","three")

#----------------------------------------#

2.10

Question:

Define a function that can accept an integer number as input and print the "It is an even number"
if the number is even, otherwise print "It is an odd number".

Hints:

Use % operator to check if a number is even or odd.

Solution

def checkValue(n):
if n%2 == 0:

print "It is an even number"

else:

print "It is an odd number"

checkValue(7)

#----------------------------------------#

2.10

Question:

Define a function which can print a dictionary where the keys are numbers between 1 and 3
(both included) and the values are square of keys.

Hints:

Use dict[key]=value pattern to put entry into a dictionary.

Use ** operator to get power of a number.

Solution
def printDict():

d=dict()

d[1]=1

d[2]=2**2

d[3]=3**2

print d

printDict()

#----------------------------------------#

2.10

Question:

Define a function which can print a dictionary where the keys are numbers between 1 and 20
(both included) and the values are square of keys.

Hints:
Use dict[key]=value pattern to put entry into a dictionary.

Use ** operator to get power of a number.

Use range() for loops.

Solution

def printDict():

d=dict()

for i in range(1,21):

d[i]=i**2

print d

printDict()

#----------------------------------------#

2.10

Question:

Define a function which can generate a dictionary where the keys are numbers between 1 and 20
(both included) and the values are square of keys. The function should just print the values only.
Hints:

Use dict[key]=value pattern to put entry into a dictionary.

Use ** operator to get power of a number.

Use range() for loops.

Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs.

Solution

def printDict():

d=dict()

for i in range(1,21):

d[i]=i**2

for (k,v) in d.items():

print v

printDict()

#----------------------------------------#

2.10
Question:

Define a function which can generate a dictionary where the keys are numbers between 1 and 20
(both included) and the values are square of keys. The function should just print the keys only.

Hints:

Use dict[key]=value pattern to put entry into a dictionary.

Use ** operator to get power of a number.

Use range() for loops.

Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs.

Solution

def printDict():

d=dict()

for i in range(1,21):

d[i]=i**2

for k in d.keys():

print k

printDict()
#----------------------------------------#

2.10

Question:

Define a function which can generate and print a list where the values are square of numbers
between 1 and 20 (both included).

Hints:

Use ** operator to get power of a number.

Use range() for loops.

Use list.append() to add values into a list.

Solution

def printList():

li=list()

for i in range(1,21):

li.append(i**2)

print li
printList()

#----------------------------------------#

2.10

Question:

Define a function which can generate a list where the values are square of numbers between 1
and 20 (both included). Then the function needs to print the first 5 elements in the list.

Hints:

Use ** operator to get power of a number.

Use range() for loops.

Use list.append() to add values into a list.

Use [n1:n2] to slice a list

Solution

def printList():

li=list()

for i in range(1,21):

li.append(i**2)
print li[:5]

printList()

#----------------------------------------#

2.10

Question:

Define a function which can generate a list where the values are square of numbers between 1
and 20 (both included). Then the function needs to print the last 5 elements in the list.

Hints:

Use ** operator to get power of a number.

Use range() for loops.

Use list.append() to add values into a list.

Use [n1:n2] to slice a list

Solution

def printList():
li=list()

for i in range(1,21):

li.append(i**2)

print li[-5:]

printList()

#----------------------------------------#

2.10

Question:

Define a function which can generate a list where the values are square of numbers between 1
and 20 (both included). Then the function needs to print all values except the first 5 elements in
the list.

Hints:

Use ** operator to get power of a number.

Use range() for loops.

Use list.append() to add values into a list.

Use [n1:n2] to slice a list


Solution

def printList():

li=list()

for i in range(1,21):

li.append(i**2)

print li[5:]

printList()

#----------------------------------------#

2.10

Question:

Define a function which can generate and print a tuple where the value are square of numbers
between 1 and 20 (both included).

Hints:

Use ** operator to get power of a number.


Use range() for loops.

Use list.append() to add values into a list.

Use tuple() to get a tuple from a list.

Solution

def printTuple():

li=list()

for i in range(1,21):

li.append(i**2)

print tuple(li)

printTuple()

#----------------------------------------#

2.10

Question:

With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half values in one line
and the last half values in one line.
Hints:

Use [n1:n2] notation to get a slice from a tuple.

Solution

tp=(1,2,3,4,5,6,7,8,9,10)

tp1=tp[:5]

tp2=tp[5:]

print tp1

print tp2

#----------------------------------------#

2.10

Question:

Write a program to generate and print another tuple whose values are even numbers in the given
tuple (1,2,3,4,5,6,7,8,9,10).

Hints:

Use "for" to iterate the tuple


Use tuple() to generate a tuple from a list.

Solution

tp=(1,2,3,4,5,6,7,8,9,10)

li=list()

for i in tp:

if tp[i]%2==0:

li.append(tp[i])

tp2=tuple(li)

print tp2

#----------------------------------------#

2.14

Question:

Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or
"Yes", otherwise print "No".

Hints:
Use if statement to judge condition.

Solution

s= raw_input()

if s=="yes" or s=="YES" or s=="Yes":

print "Yes"

else:

print "No"

#----------------------------------------#

3.4

Question:

Write a program which can filter even numbers in a list by using filter function. The list is:
[1,2,3,4,5,6,7,8,9,10].

Hints:

Use filter() to filter some elements in a list.


Use lambda to define anonymous functions.

Solution

li = [1,2,3,4,5,6,7,8,9,10]

evenNumbers = filter(lambda x: x%2==0, li)

print evenNumbers

#----------------------------------------#

3.4

Question:

Write a program which can map() to make a list whose elements are square of elements in
[1,2,3,4,5,6,7,8,9,10].

Hints:

Use map() to generate a list.

Use lambda to define anonymous functions.

Solution

li = [1,2,3,4,5,6,7,8,9,10]
squaredNumbers = map(lambda x: x**2, li)

print squaredNumbers

#----------------------------------------#

3.5

Question:

Write a program which can map() and filter() to make a list whose elements are square of even
number in [1,2,3,4,5,6,7,8,9,10].

Hints:

Use map() to generate a list.

Use filter() to filter elements of a list.

Use lambda to define anonymous functions.

Solution

li = [1,2,3,4,5,6,7,8,9,10]

evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li))

print evenNumbers
#----------------------------------------#

3.5

Question:

Write a program which can filter() to make a list whose elements are even number between 1
and 20 (both included).

Hints:

Use filter() to filter elements of a list.

Use lambda to define anonymous functions.

Solution

evenNumbers = filter(lambda x: x%2==0, range(1,21))

print evenNumbers

#----------------------------------------#

3.5
Question:

Write a program which can map() to make a list whose elements are square of numbers between
1 and 20 (both included).

Hints:

Use map() to generate a list.

Use lambda to define anonymous functions.

Solution

squaredNumbers = map(lambda x: x**2, range(1,21))

print squaredNumbers

#----------------------------------------#

7.2

Question:

Define a class named American which has a static method called printNationality.
Hints:

Use @staticmethod decorator to define class static method.

Solution

class American(object):

@staticmethod

def printNationality():

print "America"

anAmerican = American()

anAmerican.printNationality()

American.printNationality()

#----------------------------------------#

7.2
Question:

Define a class named American and its subclass NewYorker.

Hints:

Use class Subclass(ParentClass) to define a subclass.

Solution:

class American(object):

pass

class NewYorker(American):

pass

anAmerican = American()

aNewYorker = NewYorker()

print anAmerican

print aNewYorker
#----------------------------------------#

7.2

Question:

Define a class named Circle which can be constructed by a radius. The Circle class has a method
which can compute the area.

Hints:

Use def methodName(self) to define a method.

Solution:

class Circle(object):

def __init__(self, r):

self.radius = r

def area(self):

return self.radius**2*3.14
aCircle = Circle(2)

print aCircle.area()

#----------------------------------------#

7.2

Define a class named Rectangle which can be constructed by a length and width. The Rectangle
class has a method which can compute the area.

Hints:

Use def methodName(self) to define a method.

Solution:
class Rectangle(object):

def __init__(self, l, w):

self.length = l

self.width = w

def area(self):

return self.length*self.width

aRectangle = Rectangle(2,10)

print aRectangle.area()

#----------------------------------------#

7.2

Define a class named Shape and its subclass Square. The Square class has an init function which
takes a length as argument. Both classes have a area function which can print the area of the
shape where Shape's area is 0 by default.

Hints:
To override a method in super class, we can define a method with the same name in the super
class.

Solution:

class Shape(object):

def __init__(self):

pass

def area(self):

return 0

class Square(Shape):

def __init__(self, l):

Shape.__init__(self)

self.length = l

def area(self):

return self.length*self.length

aSquare= Square(3)
print aSquare.area()

#----------------------------------------#

Please raise a RuntimeError exception.

Hints:

Use raise() to raise an exception.

Solution:

raise RuntimeError('something wrong')


#----------------------------------------#

Write a function to compute 5/0 and use try/except to catch the exceptions.

Hints:

Use try/except to catch exceptions.

Solution:

def throws():

return 5/0

try:

throws()

except ZeroDivisionError:

print "division by zero!"

except Exception, err:

print 'Caught an exception'

finally:
print 'In finally block for cleanup'

#----------------------------------------#

Define a custom exception class which takes a string message as attribute.

Hints:

To define a custom exception, we need to define a class inherited from Exception.

Solution:

class MyError(Exception):

"""My own exception class

Attributes:

msg -- explanation of the error

"""

def __init__(self, msg):

self.msg = msg
error = MyError("something wrong")

#----------------------------------------#

Question:

Assuming that we have some email addresses in the "username@companyname.com" format,


please write program to print the user name of a given email address. Both user names and
company names are composed of letters only.

Example:

If the following email address is given as input to the program:

john@google.com

Then, the output of the program should be:

john

In case of input data being supplied to the question, it should be assumed to be a console input.

Hints:

Use \w to match letters.


Solution:

import re

emailAddress = raw_input()

pat2 = "(\w+)@((\w+\.)+(com))"

r2 = re.match(pat2,emailAddress)

print r2.group(1)

#----------------------------------------#

Question:

Assuming that we have some email addresses in the "username@companyname.com" format,


please write program to print the company name of a given email address. Both user names and
company names are composed of letters only.

Example:

If the following email address is given as input to the program:

john@google.com

Then, the output of the program should be:


google

In case of input data being supplied to the question, it should be assumed to be a console input.

Hints:

Use \w to match letters.

Solution:

import re

emailAddress = raw_input()

pat2 = "(\w+)@(\w+)\.(com)"

r2 = re.match(pat2,emailAddress)

print r2.group(2)

#----------------------------------------#

Question:
Write a program which accepts a sequence of words separated by whitespace as input to print the
words composed of digits only.

Example:

If the following words is given as input to the program:

2 cats and 3 dogs.

Then, the output of the program should be:

['2', '3']

In case of input data being supplied to the question, it should be assumed to be a console input.

Hints:

Use re.findall() to find all substring using regex.

Solution:

import re

s = raw_input()

print re.findall("\d+",s)
#----------------------------------------#

Question:

Print a unicode string "hello world".

Hints:

Use u'strings' format to define unicode string.

Solution:

unicodeString = u"hello world!"

print unicodeString

#----------------------------------------#

Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8.

Hints:
Use unicode() function to convert.

Solution:

s = raw_input()

u = unicode( s ,"utf-8")

print u

#----------------------------------------#

Question:

Write a special comment to indicate a Python source code file is in unicode.

Hints:

Solution:

# -*- coding: utf-8 -*-

#----------------------------------------#

Question:
Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0).

Example:

If the following n is given as input to the program:

Then, the output of the program should be:

3.55

In case of input data being supplied to the question, it should be assumed to be a console input.

Hints:

Use float() to convert an integer to a float

Solution:

n=int(raw_input())

sum=0.0
for i in range(1,n+1):

sum += float(float(i)/(i+1))

print sum

#----------------------------------------#

Question:

Write a program to compute:

f(n)=f(n-1)+100 when n>0

and f(0)=1

with a given n input by console (n>0).

Example:

If the following n is given as input to the program:

Then, the output of the program should be:


500

In case of input data being supplied to the question, it should be assumed to be a console input.

Hints:

We can define recursive function in Python.

Solution:

def f(n):

if n==0:

return 0

else:

return f(n-1)+100

n=int(raw_input())

print f(n)

#----------------------------------------#

Question:
The Fibonacci Sequence is computed based on the following formula:

f(n)=0 if n=0

f(n)=1 if n=1

f(n)=f(n-1)+f(n-2) if n>1

Please write a program to compute the value of f(n) with a given n input by console.

Example:

If the following n is given as input to the program:

Then, the output of the program should be:

13

In case of input data being supplied to the question, it should be assumed to be a console input.
Hints:

We can define recursive function in Python.

Solution:

def f(n):

if n == 0: return 0

elif n == 1: return 1

else: return f(n-1)+f(n-2)

n=int(raw_input())

print f(n)

#----------------------------------------#

#----------------------------------------#

Question:

The Fibonacci Sequence is computed based on the following formula:


f(n)=0 if n=0

f(n)=1 if n=1

f(n)=f(n-1)+f(n-2) if n>1

Please write a program using list comprehension to print the Fibonacci Sequence in comma
separated form with a given n input by console.

Example:

If the following n is given as input to the program:

Then, the output of the program should be:

0,1,1,2,3,5,8,13

Hints:

We can define recursive function in Python.

Use list comprehension to generate a list from an existing list.


Use string.join() to join a list of strings.

In case of input data being supplied to the question, it should be assumed to be a console input.

Solution:

def f(n):

if n == 0: return 0

elif n == 1: return 1

else: return f(n-1)+f(n-2)

n=int(raw_input())

values = [str(f(x)) for x in range(0, n+1)]

print ",".join(values)

#----------------------------------------#

Question:

Please write a program using generator to print the even numbers between 0 and n in comma
separated form while n is input by console.
Example:

If the following n is given as input to the program:

10

Then, the output of the program should be:

0,2,4,6,8,10

Hints:

Use yield to produce the next value in generator.

In case of input data being supplied to the question, it should be assumed to be a console input.

Solution:

def EvenGenerator(n):

i=0

while i<=n:

if i%2==0:
yield i

i+=1

n=int(raw_input())

values = []

for i in EvenGenerator(n):

values.append(str(i))

print ",".join(values)

#----------------------------------------#

Question:

Please write a program using generator to print the numbers which can be divisible by 5 and 7
between 0 and n in comma separated form while n is input by console.

Example:

If the following n is given as input to the program:


100

Then, the output of the program should be:

0,35,70

Hints:

Use yield to produce the next value in generator.

In case of input data being supplied to the question, it should be assumed to be a console input.

Solution:

def NumGenerator(n):

for i in range(n+1):

if i%5==0 and i%7==0:

yield i

n=int(raw_input())

values = []

for i in NumGenerator(n):

values.append(str(i))
print ",".join(values)

#----------------------------------------#

Question:

Please write assert statements to verify that every number in the list [2,4,6,8] is even.

Hints:

Use "assert expression" to make assertion.

Solution:

li = [2,4,6,8]

for i in li:

assert i%2==0
#----------------------------------------#

Question:

Please write a program which accepts basic mathematic expression from console and print the
evaluation result.

Example:

If the following string is given as input to the program:

35+3

Then, the output of the program should be:

38

Hints:

Use eval() to evaluate an expression.

Solution:
expression = raw_input()

print eval(expression)

#----------------------------------------#

Question:

Please write a binary search function which searches an item in a sorted list. The function should
return the index of element to be searched in the list.

Hints:

Use if/elif to deal with conditions.

Solution:

import math

def bin_search(li, element):

bottom = 0

top = len(li)-1
index = -1

while top>=bottom and index==-1:

mid = int(math.floor((top+bottom)/2.0))

if li[mid]==element:

index = mid

elif li[mid]>element:

top = mid-1

else:

bottom = mid+1

return index

li=[2,5,7,9,11,17,222]

print bin_search(li,11)

print bin_search(li,12)

#----------------------------------------#

Question:
Please write a binary search function which searches an item in a sorted list. The function should
return the index of element to be searched in the list.

Hints:

Use if/elif to deal with conditions.

Solution:

import math

def bin_search(li, element):

bottom = 0

top = len(li)-1

index = -1

while top>=bottom and index==-1:

mid = int(math.floor((top+bottom)/2.0))

if li[mid]==element:

index = mid

elif li[mid]>element:

top = mid-1
else:

bottom = mid+1

return index

li=[2,5,7,9,11,17,222]

print bin_search(li,11)

print bin_search(li,12)

#----------------------------------------#

Question:

Please generate a random float where the value is between 10 and 100 using Python math
module.

Hints:

Use random.random() to generate a random float in [0,1].


Solution:

import random

print random.random()*100

#----------------------------------------#

Question:

Please generate a random float where the value is between 5 and 95 using Python math module.

Hints:

Use random.random() to generate a random float in [0,1].

Solution:

import random

print random.random()*100-5
#----------------------------------------#

Question:

Please write a program to output a random even number between 0 and 10 inclusive using
random module and list comprehension.

Hints:

Use random.choice() to a random element from a list.

Solution:

import random

print random.choice([i for i in range(11) if i%2==0])

#----------------------------------------#

Question:
Please write a program to output a random number, which is divisible by 5 and 7, between 0 and
10 inclusive using random module and list comprehension.

Hints:

Use random.choice() to a random element from a list.

Solution:

import random

print random.choice([i for i in range(201) if i%5==0 and i%7==0])

#----------------------------------------#

Question:

Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive.
Hints:

Use random.sample() to generate a list of random values.

Solution:

import random

print random.sample(range(100), 5)

#----------------------------------------#

Question:

Please write a program to randomly generate a list with 5 even numbers between 100 and 200
inclusive.

Hints:

Use random.sample() to generate a list of random values.


Solution:

import random

print random.sample([i for i in range(100,201) if i%2==0], 5)

#----------------------------------------#

Question:

Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and
7 , between 1 and 1000 inclusive.

Hints:

Use random.sample() to generate a list of random values.

Solution:

import random

print random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5)


#----------------------------------------#

Question:

Please write a program to randomly print a integer number between 7 and 15 inclusive.

Hints:

Use random.randrange() to a random integer in a given range.

Solution:

import random

print random.randrange(7,16)

#----------------------------------------#

Question:
Please write a program to compress and decompress the string "hello world!hello world!hello
world!hello world!".

Hints:

Use zlib.compress() and zlib.decompress() to compress and decompress a string.

Solution:

import zlib

s = 'hello world!hello world!hello world!hello world!'

t = zlib.compress(s)

print t

print zlib.decompress(t)

#----------------------------------------#

Question:

Please write a program to print the running time of execution of "1+1" for 100 times.
Hints:

Use timeit() function to measure the running time.

Solution:

from timeit import Timer

t = Timer("for i in range(100):1+1")

print t.timeit()

#----------------------------------------#

Question:

Please write a program to shuffle and print the list [3,6,7,8].

Hints:

Use shuffle() function to shuffle a list.

Solution:
from random import shuffle

li = [3,6,7,8]

shuffle(li)

print li

#----------------------------------------#

Question:

Please write a program to shuffle and print the list [3,6,7,8].

Hints:

Use shuffle() function to shuffle a list.

Solution:

from random import shuffle

li = [3,6,7,8]

shuffle(li)
print li

#----------------------------------------#

Question:

Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in
["Play", "Love"] and the object is in ["Hockey","Football"].

Hints:

Use list[index] notation to get a element from a list.

Solution:

subjects=["I", "You"]

verbs=["Play", "Love"]

objects=["Hockey","Football"]

for i in range(len(subjects)):

for j in range(len(verbs)):

for k in range(len(objects)):

sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k])


print sentence

#----------------------------------------#

Please write a program to print the list after removing delete even numbers in
[5,6,77,45,22,12,24].

Hints:

Use list comprehension to delete a bunch of element from a list.

Solution:

li = [5,6,77,45,22,12,24]

li = [x for x in li if x%2!=0]

print li

#----------------------------------------#

Question:

By using list comprehension, please write a program to print the list after removing delete
numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155].

Hints:
Use list comprehension to delete a bunch of element from a list.

Solution:

li = [12,24,35,70,88,120,155]

li = [x for x in li if x%5!=0 and x%7!=0]

print li

#----------------------------------------#

Question:

By using list comprehension, please write a program to print the list after removing the 0th, 2nd,
4th,6th numbers in [12,24,35,70,88,120,155].

Hints:

Use list comprehension to delete a bunch of element from a list.

Use enumerate() to get (index, value) tuple.

Solution:

li = [12,24,35,70,88,120,155]
li = [x for (i,x) in enumerate(li) if i%2!=0]

print li

#----------------------------------------#

Question:

By using list comprehension, please write a program generate a 3*5*8 3D array whose each
element is 0.

Hints:

Use list comprehension to make an array.

Solution:

array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)]

print array

#----------------------------------------#

Question:

By using list comprehension, please write a program to print the list after removing the
0th,4th,5th numbers in [12,24,35,70,88,120,155].

Hints:

Use list comprehension to delete a bunch of element from a list.

Use enumerate() to get (index, value) tuple.

Solution:

li = [12,24,35,70,88,120,155]

li = [x for (i,x) in enumerate(li) if i not in (0,4,5)]

print li

#----------------------------------------#

Question:

By using list comprehension, please write a program to print the list after removing the value 24
in [12,24,35,24,88,120,155].

Hints:
Use list's remove method to delete a value.

Solution:

li = [12,24,35,24,88,120,155]

li = [x for x in li if x!=24]

print li

#----------------------------------------#

Question:

With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a
list whose elements are intersection of the above given lists.

Hints:

Use set() and "&=" to do set intersection operation.

Solution:

set1=set([1,3,6,78,35,55])

set2=set([12,24,35,24,88,120,155])
set1 &= set2

li=list(set1)

print li

#----------------------------------------#

With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after
removing all duplicate values with original order reserved.

Hints:

Use set() to store a number of values without duplicate.

Solution:

def removeDuplicate( li ):

newli=[]

seen = set()

for item in li:

if item not in seen:

seen.add( item )

newli.append(item)
return newli

li=[12,24,35,24,88,120,155,88,120,155]

print removeDuplicate(li)

#----------------------------------------#

Question:

Define a class Person and its two child classes: Male and Female. All classes have a method
"getGender" which can print "Male" for Male class and "Female" for Female class.

Hints:

Use Subclass(Parentclass) to define a child class.

Solution:

class Person(object):

def getGender( self ):

return "Unknown"

class Male( Person ):


def getGender( self ):

return "Male"

class Female( Person ):

def getGender( self ):

return "Female"

aMale = Male()

aFemale= Female()

print aMale.getGender()

print aFemale.getGender()

#----------------------------------------#

Question:

Please write a program which count and print the numbers of each character in a string input by
console.

Example:

If the following string is given as input to the program:


abcdefgabc

Then, the output of the program should be:

a,2

c,2

b,2

e,1

d,1

g,1

f,1

Hints:

Use dict to store key/value pairs.

Use dict.get() method to lookup a key with default value.

Solution:

dic = {}

s=raw_input()

for s in s:
dic[s] = dic.get(s,0)+1

print '\n'.join(['%s,%s' % (k, v) for k, v in dic.items()])

#----------------------------------------#

Question:

Please write a program which accepts a string from console and print it in reverse order.

Example:

If the following string is given as input to the program:

rise to vote sir

Then, the output of the program should be:

ris etov ot esir

Hints:

Use list[::-1] to iterate a list in a reverse order.


Solution:

s=raw_input()

s = s[::-1]

print s

#----------------------------------------#

Question:

Please write a program which accepts a string from console and print the characters that have
even indexes.

Example:

If the following string is given as input to the program:

H1e2l3l4o5w6o7r8l9d

Then, the output of the program should be:

Helloworld
Hints:

Use list[::2] to iterate a list by step 2.

Solution:

s=raw_input()

s = s[::2]

print s

#----------------------------------------#

Question:

Please write a program which prints all permutations of [1,2,3]

Hints:

Use itertools.permutations() to get permutations of list.

Solution:

import itertools
print list(itertools.permutations([1,2,3]))

#----------------------------------------#

Question:

Write a program to solve a classic ancient Chinese puzzle:

We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and
how many chickens do we have?

Hint:

Use for loop to iterate all possible solutions.

Solution:

def solve(numheads,numlegs):

ns='No solutions!'

for i in range(numheads+1):

j=numheads-i

if 2*i+4*j==numlegs:

return i,j

return ns,ns
numheads=35

numlegs=94

solutions=solve(numheads,numlegs)

print solutions

#----------------------------------------#