Thursday, 13 December 2012

Adding Mercurial (hg) completion to OS X

Being new to Mercurial, I really wanted to have bash completion for it. But figuring out the paths is really difficult for OS X with not many people writing about it.

To add hg-completion to your terminal:
  1. Download bash code from
  2. Save the downloaded file as hg-completion.bash to your /opt/local/etc/profile.d directory
  3. Run the script whenever you open a new terminal by adding following line to your ~/.profile
  4. Open a new Tab and enjoy!
Similar code for hg completion can be found at, but the things are working quite good for me already. Try it if you'd like.

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

Sunday, 9 December 2012

Solved: locale error in Python on OS X

I was amused by the following error I got on my Mac terminal today :
How can the Mac not know about UTF-8?
I checked my current locale:
Searching for the reason, I stumbled upon this stackoverflow question. So, UTF-8 isn't a valid OS X locale by default!
Now, the stackoverflow question said, the problem can be solved by setting your locale to UTF-8 explicitly. Thus, I used the export command to set the environment variables of locale to my required locale i.e. UTF-8
And the locale became:
This pretty much solved my problem. But being an avid lover of python, I was soon disgusted to do this every time I opened a new shell. So, I added the above commands to my ~/.profile ;) . Thus, now whenever I restart/start a shell, The locale is set to UTF-8 automatically. I haven't noticed any side issues with this yet, but my python experience has become better. :)

PS: To see the locales supported by your system, you can use locale -a

Thursday, 6 December 2012

Sample Twitter app for iOS

I recently created a project on github to learn iOS development. The app uses Twitter API to get your feeds and data.

One thing you can see in it is that it is designed for iOS 6.0 (iPhone 5). There are many good features added to iOS 6.0 that makes the development pretty much easier and you don't have to use third party modules to get your work done.

The link to the project is :

Some things to look for in the project:
  1. Using twitter credentials from iOS itself. (docs)
  2. JSON serialisation provided by apple itself. (docs)
  3. Pull to refresh control. (docs)
  4. Loading images asynchronously without use of any third party modules. 
  5. Storyboards!
  6. Using NSCache. (docs)
  7. etc.