Wednesday, 12 December 2012

Some good python interview questions

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)
  • datetime               (used to manipulate date and time) 
  • re                         (regular expressions) 
  • urllib, urllib2        (handles many HTTP things) 
  • string                   (a collection of different groups of strings for example all lower_case letters etc) 
  • itertools               (permutations, combinations and other useful iterables) 
  • ctypes                  (from python docs: create and manipulate C data types in Python) 
  • email                    (from python docs: A package for parsing, handling, and generating email messages) 
  • __future__           (Record of incompatible language changes. like division operator is different and much better when imported from __future__) 
  • sqlite3                  (handles database of SQLite type) 
  • unittest                 (from python docs: Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's Smalltalk testing framework) 
  • xml                      (xml support) 
  • logging                (defines logger classes. enables python to log details on severity level basis) 
  • os                         (operating system support) 
  • pickle                   (similar to json. can put any data structure to external files) 
  • subprocess           (from docs: This module allows you to spawn processes, connect to their input/output/error pipes, and obtain their return codes) 
  • webbrowser        (from docs: Interfaces for launching and remotely controlling Web browsers.) 
  • traceback             (Extract, format and print Python stack traces) 
2. Name a module that is not included in python by default
 mechanize django gtk A lot of other can be found at pypi.

3. What is used for?
 It declares that the given directory is a module package. #Python Docs (From Endophage's comment) 

4. What is pass used for?
 "pass" does nothing. It is used for completing the code where we need something. For eg:

5. What is a docstring?
 docstring is the documentation string for a function. It can be accessed by It is declared as: *Writing documentation for your progams is a good habit and makes the code more readable, understandable and thus reusable.

6. What is list comprehension?
 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:
#Python Docs

8. What is the difference between a tuple and a list?
 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.
 tuple initialization: a = (2,4,5)
 list initialization: a = [2,4,5]
 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'

10. What would the following code yield?

 Ans: 'abcdefghij' will be printed. This is called string slicing. Since here the indices of the two slices are colliding, the string slices are 'abc' and 'defghij'. The '+' operator on strings concatenates them. Thus, the two slices formed are concatenated to give the answer 'abcdefghij'.

11. Optimize these statements as a python programmer.  Ans:

 12. Write a program to print all the contents of a file.

 13. What will be the output of the following code Ans. 2 2 The second line is a simultaneous declaration i.e. value of new a is not used when doing b=a+1. This is why, exchanging numbers is as easy as: :D

 14. Given the list below remove the repetition of an element. All the elements should be unique words = ['one', 'one', 'two', 'three', 'three', 'two']
 Ans: A bad solution would be to iterate over the list and checking for copies somehow and then remove them!
 One of the best solutions I can think of right now: 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 {'one':2, 'two':2, 'three':2}
 Ans: Without using try-catch block:
 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. Can be checked by a single statement (pythonic beauty):

 17. Demonstrate the use of exception handling in python.
 Ans. ## here you have atleast 1 module imported as me. This is used to check if the users computer has third party libraries that we need. If not, we work with a default library of python. Quite useful in updating softwares.
 PS: This is just one of the uses of try-except blocks. You can note a good use of these in API's. Also note that if we do not define the error to be matched, the except block would catch any error raised in try block.

 18. Print the length of each line in the file 'file.txt' not including any whitespaces at the end of the lines. #OR to cram to two lines: rstrip() is an inbuilt function which strips spaces or tabs (whitespace characters) from the right end of the string.

19. Print the sum of digits of numbers starting from 1 to 100 (inclusive of both)
 Ans. 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.
 Another one suggested by David using maps:

 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: 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.! 

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() # The lists have an inbuilt function, sort() sorted(nums) # sorted() is one of the inbuilt functions) 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 (Thanks endophage for correcting this) #OR

 24. The following code is supposed to remove numbers less than 5 from list n, but there is a bug. Fix the bug. ## after e is removed, the index position gets disturbed. Instead it should be: OR again a list comprehension: ;) OR use filter  

25. What will be the output of the following  Ans. Here the output is : {}  #Empty Dictionay x is a normal value, so it takes 1.. y is a list of numbers, so it takes 2,3.. z wants named parameters, so it can not take any value here. Thus the given answer.

 26. Write a program to swap two numbers.
 a = 5
 b = 9
 as i told earlier too, just use:
a,b = b,a

 27. What will be the output of the following code
 Ans. All the outputs will be 1, since the value of the the object's attribute(x) is never changed. 1 1 1 1 x is now a part of the public members of the class C. Thus it can be accessed directly..

 28. What is wrong with the code
  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.
 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

 29. What all options will work?
 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 not work as assignment can not be done in print command like this
 d. 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

 30. In Python function parameters are passed by value or by reference?
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: 

 31.Remove the whitespaces from the string. s = 'aaa bbb ccc ddd eee' Ans. OR
 32. What does the below mean?  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.

 33. Optimize the below code The above code adds a trailing s after each element of the list.
 34. If given the first and last names of bunch of employees how would you store it and what datatype?
 Ans. Best stored in a list of dictionaries. Dictionary format :  {'first_name' : 'Ayush', 'last_name' : 'Goel'}

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. Up-vote/share the post if you liked it. Thanks!

Note: This has been ported from my Wordpress Blog. The valuable old comments still remain there, if you are interested. :)