Feb 13, 2013

Python Interview Questions - Part 1


1) Get Unique Items in an array :

Set : Another data type in Python, where copies are not allowed.
List: Sequence of elements just like array

>>> a = [1, 2, 2, 3]

>>> set(a)
{1, 2, 3} #Flower brackets

>>> list(set(a))
[1, 2, 3]

>>> langs = ['Perl', 'PHP', 'Python', 'Java', 'C', 'Ruby', 'perl', 'Perl', 'PERL']
>>> for each_lang in sorted(set(langs)):
...     print each_lang

O/P:
C
Java
PERL
PHP
Perl
Python
Ruby
perl


2) What is a docstring in Python?

Docstring is the documentation string for a function.
It prints the comments given inside the function
It can be accessed by <function_name>.__doc__

>>>def func_test():
""" Test Comments 1
Test Comments 2
Test Comments 3 """

>>> func_test.__doc__


3) How to loop/iterate through dict in Python

>>> Countries = {'India': 'New Delhi', 'USA': 'Washington', 'China' : 'Beijing', 'Japan' : 'Tokyo'}

>>> for country, capital in Countries.iteritems(): #Old Version
...     print country, capital
...

>>> for country, capital in Countries.items(): #New Version
...     print(country, capital)
...
India New Delhi
China Beijing
USA Washington
Japan Tokyo


4) How to Strip End of Line chars in Python (e.g., \n)

rstrip()

C:\Prabhath\Technical\Python\Python_Scripts\read.txt
Gandhi
Abraham Lincoln
Winston Churchill

>>> file = open("C:\\Prabhath\\Technical\\Python\\Python_Scripts\\read.txt", "r")
>>> text = file.readlines()
>>> file.close()

>>> for line in text:
>>> print (len(line.rstrip()))


rstrip() is an inbuilt function which strips the string from the right end of spaces or tabs (special chars like \n etc.,)

Output:
6
15
17


5) Sorting an Array in Python

>>>arr_sort = [10, 50, 90, 80, 35, 56, 45, 98]

>>>arr_sort.sort() #It will sort and keep the result in arr_sort
>>>arr_sort #When U print this, it shows the result [10, 35, 45, 50, 56, 80, 90, 98]

sorted(x) #prints the result [10, 35, 45, 50, 56, 80, 90, 98]


list.sort vs sorted()
list.sort() #sortls only lists
sorted() function accepts any iterable

e.g.,
>>> sorted("Python in demand NOW".split(), key=str.lower)
['demand', 'in', 'NOW', 'Python']


6) Convert Strings to Integers

>>>num_strs = ['11','121','153','184','150','166','17','138','19']
>>>num_int = [int(i) for in in num_strs] #[11, 121, 153, 184, 150, 166, 17, 138, 19]

(or)
>>>num_strs = ['11','121','153','184','150','166','17','138','19']
>>>list(map(int, num_strs)) #[11, 121, 153, 184, 150, 166, 17, 138, 19]
>>>map(int, num_strs) #<map object at 0x0000000002A7AF28>


7) Program to swap two numbers (Python)

a = 500
b = 900

>>>a,b = b,a


8) How to use join in Python

>>> ss = 'abc def ghi'

>>> ss.split() #splits based on space, equivalent to ss.split("\s")
['abc', 'def', 'ghi']

>>> ''.join(ss.split())
'abcdefghi'