1.
Name five modules that are included in python by default
2. Name a module that is not included in python by default
3. What is __init__.py used for?
4. When is pass used for?
5. What is a docstring?
6. What is list comprehension?
7. What is map?
8. What is the difference between a tuple and a list?
Ans. This is the most frequently asked question on python.
A tuple is a list that is immutable. A list is mutable i.e. The members can be changed and altered
but a tuple is immutable i.e. the members cannot be changed.
Other significant difference is of the syntax. A list is defined as
list1 = [1,2,5,8,5,3,]
list2 = ["Sachin", "Ramesh", "Tendulkar"]
A tuple is defined in the following way
tup1 = (1,4,2,4,6,7,8)
tup2 = ("Sachin","Ramesh", "Tendulkar")
So the difference is in the type of brackets.
Coding questions
9. Using various python modules convert the list a to generate the output 'one, two, three'
a = ['one', 'two', 'three']
ANSWER:
>>> a = ['one','two','three']
>>> ','.join(a)
'one,two,three'
10. What would the following code yield?
word = 'abcdefghij'
print word[:3] + word[3:]
Ans. This will print the word 'abcdefghij'
11. Optimize these statements as a python programmer
word = 'word'
print word.__len__()
ANSWER:
>>> print 'word'.__len__()
4
12. Write a program to print all the contents of a file
Ans.
try:
f1=open("filename.txt","r")
except Exception, e:
print "%s" %e
print f1.readlines()
ANSWER2:
with open("tmp1.txt", "r") as f:
f.readlines()
13. What will be the output of the following code
a=1
a, b=a+1, a+1
print a
print b
Ans.
2
2
Here in the second line a,b=a+1,a+1 means that a=a+1 and b=a+1 which is 2. But this is the
python way of initialization which a python programmer should understand.
14. Given the list below remove the repetition of an element. All the elements should be
uniquewords = ['one', 'one', 'two', 'three', 'three', 'two']
ANSWER:
>>> set(uniquewords)
set(['three', 'two', 'one'])
15. Iterate over a list of words and use a dictionary to keep track of the frequency(count) of
each word. for example
{'one':2,'two':2,'three':2}
ANSWER:
>>> l = ['one', 'one', 'two', 'three', 'three', 'two', 'one', 'one', 'two']
>>> d = {}
>>> for w in l:
... d[w] = 1 + d.get(w,0)
...
>>> d
{'three': 2, 'two': 3, 'one': 4}
16.Write the following logic in Python:
If a list of words is empty, then let the user know it's empty, otherwise let the user know it's
not empty.
Ans.
a=[]
if len(a):
print"The list is not empty"
else:
print"The list is empty"
17. Demonstrate the use of exception handling in python.
Ans.
a=[1,2,3,4]
try:
print a[5]
except Exception, e # This was important. Just do not say except: and print out something. It is
print e # Important to know what is the error
>>> a=[1,2,3,4]
>>> try:
... print a[5]
... except Exception, e:
... print "Error %s" % e
...
Error list index out of range
18. Print the length of each line in the file 'file.txt' not including any whitespaces at the end
of the lines.
Ans.
>>> f1 = open("abc.py", 'r')
>>> i=0
>>> for line in iter(f1):
... print "Length of line %d is %d" % (i, len(line.rstrip()))
... i+=1
...
Length of line 0 is 11
Length of line 1 is 21
19. Print the sum of digits of numbers starting from 1 to 100
Ans. print sum(range(1,101))
This is way too easy but just who know python. Since I am a C++ Programmer, I started writing
a for loop to add up which was way too dumb. Hope you don't make this mistake.
Python is known for it short syntax and easy to use functions.
20. Create a new list that converts the following list of number strings to a list of numbers.
num_strings = ['1','21','53','84','50','66','7','38','9']
Ans.
>>>num_strings = ['1','21','53','84','50','66','7','38','9']
>>>[int(j) for j in num_strings]
[1, 21, 53, 84, 50, 66, 7, 38, 9]
21. Create two new lists one with odd numbers and other with even numbers
num_strings = [1,21,53,84,50,66,7,38,9]
Ans.
>>>num_strings = [1,21,53,84,50,66,7,38,9]
>>>o, e = [], []
>>>[o.append(n) if n % 2 else e.append(n) for n in num_strings]
[None, None, None, None, None, None, None, None, None]
>>>o,e
([1, 21, 53, 7, 9], [84, 50, 66, 38])
>>> num_strings = [1,21,53,84,50,66,7,38,9]
>>> odd, even = filter(lambda x:x%2, num_strings), filter(lambda x: not x%2, num_strings)
>>> print odd,even
[1, 21, 53, 7, 9] [84, 50, 66, 38]
22. Write a program to sort the following intergers in list
nums = [1,5,2,10,3,45,23,1,4,7,9]
nums.sort() # This is the quickest sorting algorithm. This is the best possible way to sort.
print nums
23. Write a for loop that prints all elements of a list and their position in the list.
abc = [4,7,3,2,5,9]
Ans.
>>>abc = [4,7,3,2,5,9]
>>>for i, v in enumerate(abc):
... print i,v
...
0 4
1 7
2 3
3 2
4 5
5 9
24. The following code is supposed to remove numbers less than 5 from list n, but there is a
bug. Fix the bug.
n = [1,2,5,10,3,100,9,24]
for e in n:
if e<5:
n.remove(e)
print n
Ans. The output here will be
[2,3,5,10,100,9,24] which means the 1st and the 5th elements are removed.
It should be implemented as below.
>>> n = [1,2,5,10,3,100,9,24]
>>> nlist = filter(lambda x: x >= 5, n)
>>> print nlist
[5, 10, 100, 9, 24]
list.remove(element) will remove the element, and shrink the list. If
you are iterating over the same list at that time, and you wanted to
go to next element, the next element may very well be the one after.
Here is what is happening in the problem: The 0th element in the list
is less than 5 and is removed, thus, making the list shorter by one
element. The next iteration in the for loop goes to n[1], but n[0]
now is 2, so the loop skips element 2 and doesn't remove it. Same
thing happens at 100, but it is ok to skip 100 as it is > 5
25. What will be the output of the following
def func(x,*y,**z):
print z
func(1,2,3)
Ans.
Here the output is :
{}
If I print all the variables, namely x, y and z it yeilds me this
1 (2,3) {}
* and ** have special usage in the function argument list. *
implies that the argument is a list and ** implies that the argument
is a dictionary. This allows functions to take arbitrary number of
arguments (like your sum function that took range of numbers from 0
.. 100. Pretty cool, eh?
26. Write a program to swap two numbers.
a = 5
b = 9
def swap(c,d):
return d,c
swap(a,b)
This will print the swapped values of a and b
(9,5)
OR if this does not seem convincing,
a, b = 5, 10
t = a
a=b
b=t
print a,b
>>> a = 5
>>> b = 10
>>> a,b=b,a
>>> a
10
>>> b
5
27. What will be the output of the following code
class C(object):
def__init__(self):
self.x =1
c=C()
print c.x
print c.x
print c.x
print c.x
Ans.
All the outputs will be 1
1
1
1
1
28. What is wrong with the code
func([1,2,3]) # explicitly passing in a list
func() # using a default empty list
def func(n = []):
#do something with n
print n
Ans. I tried running the code with my addition of printing the value of n in the function and
found out the following result
func([1,2,3]) resulted in [1,2,3]
while func() resulted in []
29. What all options will work?
a.
n=1
print n++
b.
n=1
print ++n
c.
n=1
print n+=1
d.
int n = 1
print n = n+1
e.
n =1
n = n+1
From the above options I believe the following will work
b. and e.
There are some problems with a, c and d.
if you try running the code in a , it does not accept n++ but it accepts ++n
n+=1 is not accepted while in d the variable is preceded by an int which is not pythonically
correct.
30. In Python function parameters are passed by value or by reference?
Ans. Please refer to this
31.Remove the whitespaces from the string.
s = 'aaa bbb ccc ddd eee'
Ans.
a = string.split(s)
print a
['aaa', 'bbb', 'ccc', 'ddd', 'eee'] # This is the output of print a
print string.join(a)
aaa bbb ccc ddd eee # This is the output of print string.join(a)
32. What does the below mean?
s = a + '[' + b + ':' + c + ']'
33. Optimize the below code
def append_s(words):
new_words=[]
for word in words:
new_words.append(word + 's')
return new_words
for word in append_s(['a','b','c']):
print word
The above code adds a trailing s after each element of the list. Is there a better way one can write
the above script?
34. If given the first and last names of bunch of employees how would you store it and what
datatype?
Ans. Either a dictionary or just a list with first and last names included in an element.
Python Related Questions
What are generator Functions?
Ans.
A generator function or generator method is one which contains a yield expression. When a
generator function is called it returns an iterator. Values are extracted from the iterator one at a
time by calling its __next__() method. At each call to __next__() the generator function’s yield
expression’s value (None if none is specified) is returned. If the generator function finishes or
executes a return a StopInteration exception is raised.
Generators provide an elegant way to write simple and efficient code for functions that return a
list of elements. Based on the yield directive, they allow you to pause a function and return an
intermediate result. The function saves its execution context and can be resumed later if
necessary.
>>> def fibonacci():
... a, b = 0,1
... while True:
... yield b
... a,b = b, a+b
...
>>> fib = fibonacci()
>>> fib.next()
1
>>> fib.next()
1
>>> fib.next()
2
>>> [fib.next() for i in range(10)]
[3, 5, 8, 13, 21, 34, 55, 89, 144, 233]
What is filter, map and reduce
MAP
One of the more common things programs do with lists and other sequences is apply an
operation to each item and collect the results. For instance, updating all the counters in a list can
be done easily with a for loop:
In [15]: counters = [1,2,3,4]
In [16]: updated = []
In [17]: for x in counters:
....: updated.append(x+10)
....:
In [18]: updated
Out[18]: [11, 12, 13, 14]
But because this is such a common operation, python actually provides a built-in that does most
of the work for you. The map function applies a passed-in function to each item in a sequence
object, and returns a list containing all the function call results. For example:
In [19]: def inc(x): return x+10
In [20]: map(inc, counters)
Out[20]: [11, 12, 13, 14]
In [21]: updated_map = map(inc,counters)
In [22]: updated_map
Out[22]: [11, 12, 13, 14]
REDUCE
At each step, reduce passes the current sum or productm, along with the enxt item from the list,
to the passed-in lambda function. By default, the first item in the sequence initializes the starting
value.
In [42]: reduce((lambda x,y:x+y), [1,2,3,4])
Out[42]: 10
In [43]: reduce((lambda x,y:x*y), [1,2,3,4])
Out[43]: 24
The reduce funtion is in functools in python 3.0. It is more complex and it accepts an iterator to
process. It is not itself an iterator. It returns a single result.
>>> from functools import reduce
>>> reduce( (lambda x, y: x * y), [1, 2, 3, 4] )
24
>>> reduce( (lambda x, y: x / y), [1, 2, 3, 4] )
0.041666666666666664
>>>
At each step, reduce passes the current product or division, along with the next item from the
list, to the passed-in lambda function. By default, the first item in the sequence initialized the
starting value. Here’s the for loop version of the first of these calls, with the multiplication hard
coded inside the loop:
>>> L = [1, 2, 3, 4]
>>> result = L[0]
>>> for x in L[1:]:
result = result * x
>>> result
24
>>>
Let’s make our own version of reduce.
>>> def myreduce(fn, seq):
tally = seq[0]
for next in seq[1:]:
tally = fn(tally, next)
return tally
>>> myreduce( (lambda x, y: x * y), [1, 2, 3, 4])
24
>>> myreduce( (lambda x, y: x / y), [1, 2, 3, 4])
0.041666666666666664
>>>
The built-in reduce also allows an optional third argument placed before the items in the
sequence to serve as a default result when the sequence is empty.
FILTER:
Filter extracts each element in the sequence for which the function returns True.
>>> list(range(-5,5))
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
>>> list(filter((lambda x:x>0), range(-5,5)))
[1, 2, 3, 4]
>>>
What is lambda?
Ans. Besides the def statement, Python also provides an expression form that generates function
objects. Because of its similarity to a tool in the LISP language, it is called lambda. Like def,
this expression creates a function to be called later, but it returns the function instead of
assigning it to a name. This is why lambdas are somtimes known as anonymous functions. In
practice, they are often used as a way to inline a function definition, or to defer execution of a
piece of code.
Lambda expressions
The lambda’s general form is the keyword lambda, followed by one or more arguments (exactly
like the arguments list you enclose in parentheses in a def header), follwed by an expression after
a colon:
lambda argument1, argument2, .... argument N: expression using arguments
Example:
Below is an example where a simple function can be written to return the addition of 3 variables
passed into the function.
>>> def func(x,y,z): return x+y+z
...
>>> func(1,2,3)
6
The same above functionality can be achieved using lambda in the following way:
>>> f = lambda x, y, z: x+y+z
>>> f(1,2,3)
6
Defaults work on lambda arguments, just like in a def:
>>> x =(lambda a='ron', b='ronak', c='patel': a+b+c)
>>> x('Mr.')
'Mr.ronakpatel'
Why use lambda?
Lambdas come in handy as a sort of function shorthand that allows you to embed a function’s
definition within the code that uses it. They are entirely optional but they tend to be simpler
coding constructions in scenarios where you just need to embed small bits of executable code.
L = [(lambda x: x**2), (lambda x: x**3), (lambda x: x**4)]
In [8]: L[0](3)
Out[8]: 9
In [9]: L[1](3)
Out[9]: 27
In [10]: L[2](3)
Out[10]: 81
In [11]: for f in L:
....: print f(2)
....:
4
8
16
The lambda expression is most useful as a shorthand for def, when you need to stuff small pieces
of executable code into places where statements are illegal syntactically.
What is global interpreter lock?
What is mapreduce?
Mapreduce is a programming model for processing large data sets, and the name of an
implmentation of the model by Google. Mapreduce is used to do distributed computing on
clusters of computers. This model is inspired by the map and reduce functions commonly used
in functional programming, although their purpose in the MapReduce framework is not the same
as their original forms.
Users specify a map function that processes a key/value pair to generate a set of intermediate
key/value pairs, and a reduce function that merges all intermediate values associated with the
same intermediate key.
Have you worked with Distributed databases?
Any python framework experience?
Algorithmic
Binary search and its complexity
Quick Sort and its complexity
Linux
If a server is not responding to your requests how would you debug?
What is the command you would use to see that a particualar process is running or not.
Scalability of databases
How would you scale your databases for number of millions of users?
How would you manage multiple instances of databases over multiple servers?
What is a generator
Explain filter, reduce, map
Explain lambda
What is a Global Interpreter Lock
Experience with distributed systems
What is riak
Any experience with web framework?
What is MapReduce
Complexity of Quick sort, binary sort,
Best algorithm to get a combination of two integers whose addition is a specific number.
How would you scale a database with multiple instances?