Some good python interview
Some good python interview
9 Votes
Some questions I had from somewhere. Since I feel somewhat capable of myself, I try to answer
them here..
Edit: After all I got that “somewhere” The writer is a fellow python enthusiast and has given
me the permission to use his questions on my blog (though the answers are to be mine.. .
Thank you Ronak..
Edit: Thanks a lot David Lawrence (Endophage) for your eminent input to modify this post.
1. Name five modules that are included in python by default (many people come searching for
this, so I included some more examples of modules which are often used)
It declares that the given directory is a module package. #Python Docs (From Endophage‘s
comment)
pass does nothing. It is used for completing the code where we need something. For eg:
1 class abc():
2 pass
5. What is a docstring?
function_name.__doc__
it is declared as:
1 def function_name():
2 """your docstring"""
Writing documentation for your progams is a good habit and makes the code more
understandable and reusable.
Creating a list by doing some operation over data that can be accessed using an iterator. For eg:
7. What is map?
map executes the function given as the first argument on all the elements of the iterable given as
the second argument. If the function given takes in more than 1 arguments, then many iterables
are given. #Follow the link to know more similar functions
For eg:
1 >>>a='ayush'
2 >>>map(ord,a)
3 .... [97, 121, 117, 115, 104]
4 >>> print map(lambda x, y: x*y**2, [1, 2, 3], [2, 4, 1])
5 .... [4, 32, 3]
03 map(...)
04 map(function, sequence[, sequence, ...]) -> list
05
06 Return a list of the results of applying the function to the items of
07 the argument sequence(s). If more than one sequence is given, the
08 function is called with an argument list consisting of the corresponding
09 item of each sequence, substituting None for missing values when not all
10 sequences have the same length. If the function is None, return a list of
11 the items of the sequence (or a list of tuples if more than one sequence).
#Python Docs
A tuple is immutable i.e. can not be changed. It can be operated on only. But a list is mutable.
Changes can be done internally to it.
The methods/functions provided with each types are also different. Check them out yourself.
9. Using various python modules convert the list a to generate the output ‘one, two, three’
1 >>>help(str.join)
2 Help on method_descriptor:
3 join(...)
4 S.join(iterable) -> string
5 Return a string which is the concatenation of the strings in the
6 iterable. The separator between elements is S.
1 word = 'abcdefghij'
2 print word[:3] + word[3:]
1 word = 'word'
2 print word.__len__()
Ans:
1 word = 'word'
2 print len(word)
Ans.
1 try:
2 with open('filename','r') as f:
3 print f.read()
4 except IOError:
5 print "no such file exists"
1a =1
2 a, b = a+1, a+1
3 print a
4 print b
Ans.
2
2
The second line is a simultaneous declaration i.e. value of new a is not used when doing b=a+1.
1 a,b = b,a
Ans:
A bad solution would be to iterate over the list and checking for copies somehow and then
remove them!
1 a = [1,2,2,3]
2 list(set(a))
set is another type available in python, where copies are not allowed. It also has some good
functions available used in set operations ( like union, difference ).
15. Iterate over a list of words and use a dictionary to keep track of the frequency(count) of each
word. for example
Ans:
01 >>> def dic(words):
02 a = {}
03 for i in words:
04 try:
05 a[i] += 1
06 except KeyError: ## the famous pythonic way:
07 a[i] = 1 ## Halt and catch fire
08 return a
09
10 >>> a='1,3,2,4,5,3,2,1,4,3,2'.split(',')
11 >>> a
12 ['1', '3', '2', '4', '5', '3', '2', '1', '4', '3', '2']
13 >>> dic(a)
14 {'1': 2, '3': 3, '2': 3, '5': 1, '4': 2}
03 for i in words:
04 data[i] = data.get(i, 0) + 1
05 return data
06
07 >>> a
08 ['1', '3', '2', '4', '5', '3', '2', '1', '4', '3', '2']
09 >>> dic(a)
10 {'1': 2, '3': 3, '2': 3, '5': 1, '4': 2}
PS: Since the collections module (which gives you the defaultdict) is written in python, I would
not recommend using it. The normal dict implementation is in C, it should be much faster. You
can use timeit module to check for comparing the two.
So, David and I have saved you the work to check it. Check the files on github. Change the data
file to test different data.
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.
1 print "The list is empty" if len(a)==0 else "The list is not empty"
2
3 >>> a=''
4 >>> print "'The list is empty'" if len(a)==0 else "'The list is not empty'"
5 'The list is empty'
6 >>> a='asd'
7 >>> print "'The list is empty'" if len(a)==0 else "'The list is not empty'"
8 'The list is not empty'
Ans.
1 try:
2 import mechanize as me
3 except ImportError:
4 import urllib as me
18. Print the length of each line in the file ‘file.txt’ not including any whitespaces at the end of
the lines.
19. Print the sum of digits of numbers starting from 1 to 100 (inclusive of both)
Ans.
1 print sum(range(1,101))
range() returns a list to the sum function containing all the numbers from 1 to 100. Please see
that the range function does not include the end given (101 here).
xrange() returns an iterator rather than a list which is less heavy on the memory.
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.
use a list comprehension
#num_strings should not contain any non-integer character else ValueError would be raised. A
try-catch block can be used to notify the user of this.
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:
1 >>> odd=[]
2 >>> even=[]
3 >>> for i in n:
4 even.append(i) if i%2==0 else odd.append(i)
5
6 ## all odd numbers in list odd
7 ## all even numbers in list even
Though if only one of the lists were requires, using list comprehension we could make:
But using this approach if both lists are required would not be efficient since this would iterate
the list two times.!
nums = [1,5,2,10,3,45,23,1,4,7,9]
Python uses TimSort for applying this function. Check the link to know more.
23. Write a for loop that prints all elements of a list and their position in the list.
Printing using String formatting
#OR
24. The following code is supposed to remove numbers less than 5 from list n, but there is a bug.
Fix the bug.
1 n = [1,2,5,10,3,100,9,24]
2
3 for e in n:
4 if e<5:
5 n.remove(e)
6 print n
## after e is removed, the index position gets disturbed. Instead it should be:
1 a=[]
2 for e in n:
3 if e >= 5:
4 a.append(e)
5n =a
OR use filter
1 def func(x,*y,**z):
2 .... print z
3
4 func(1,2,3)
Ans.
{} #Empty Dictionay
a=5
b=9
1 class C(object):
2 .... def__init__(self):
3 .... self.x =1
4
5 c=C()
6 print c.x
7 print c.x
8 print c.x
9 print c.x
Ans.
All the outputs will be 1, since the value of the the object’s attribute(x) is never changed.
1
1
1
1
3
4 def func(n = []):
5 #do something with n
6
7 print n
Ans. This would result in a NameError. The variable n is local to function func and can’t be
accessesd outside. So, printing it won’t be possible.
a.
n=1
print n++ ## no such operator in python (++)
b.
n=1
print ++n ## no such operator in python (++)
c.
n=1
print n += 1 ## will work
d.
int n = 1
print n = n+1 ##will not work as assignment can not be done in print command like this
e.
n =1
n = n+1 ## will work
Edit: An extra point for interviews given by Shane Green and Peter: “”"Another thing is that
mutable types should never be used as default parameter values. Default parameter value
expressions are only evaluated once, meaning every invocation of that method shares the same
default value. If one invocation that ends up using the default value modifies that value–a list, in
this case–it will forever be modified for all future invocations. So default parameter values
should limited to primitives, strings, and tuples; no lists, dictionaries, or complex object
instances.”"”
Reference: Default argument values
30. In Python function parameters are passed by value or by reference?
Ans. By value (check if you want to, I also did the same It is somewhat more complicated than
I have written here (Thanks David for pointing). Explaining all here won’t be possible. Some
good links that would really make you understand how things are:
Stackoverflow
Ans.
1 ''.join(s.split())
2 ## join without spaces the string after splitting it
OR
1 filter(lambda x: x != ‘ ‘, s)
seems like a string is being concatenated. Nothing much can be said without knowing types of
variables a, b, c. Also, if all of the a, b, c are not of type string, TypeError would be raised. This
is because of the string constants (‘[' , ']‘) used in the statement.
1 def append_s(words):
2 new_words=[]
The above code adds a trailing s after each element of the list.
def append_s(words):
return [i+'s' for i in words] ## another list comprehension
34. If given the first and last names of bunch of employees how would you store it and what
datatype?
Since most of the code here gets messed up, I have created a repo on github named Python(blog)
which lists all the required code.