May 5, 2015

Python questions and answers - Part 1

1. What is floor division in python ?  OR What is difference between operator / and // ?
Answer: Operator // is called floor division in python.Integer division was a concern for  python developer prior to python 2.2. Python 2.2 came up with new operator to support
floor division and regardless of input type.  i.e :  // always gives floor result.
Note :-
In Python 3, / is float division
In Python 2, / is integer division (assuming int inputs)
In both 2 and 3, // is integer division
In Python 2.x, make sure to have at least one operand of your division in float. \
Consider following example for better understanding, (I am using python 2.7)
>>> 20/14  #Integer outcome
1
>>> float(20)/12  # floating outcome since one of the operand is float
1.6666666666666667

2. What will be outcome of following snippet ? / What are First-Class Objects in python ?
>>>def disply_msg():
             print 'hello world from function'
>>>x = disply_msg #Function assigned to an identifier
>>>x()  
Answer: It will display "hello world from function" .
The fundamental behind is that, functions are first-class types in Python. First-class objects are instances of a type that can be assigned to an identifier, passed as a parameter, or returned by
a function.So, x = function executes, x becomes alias of function disply_msg and when x() executes definition of disply_msg executes and display hello world from function.
Notes :
  1. function can also be passed as argument of function.For example, inbuilt function min and max passed abs function to calculate minimum absolute value.
    >>>min(12, -34, key=abs)  # abs(-34) > abs(12), so display 12
    12
  2. In python, class are also first class object. 
3. Swap values of two variable in python without using temporary variable.Consider a =8, b= 9
and after swapping be a = 9, b= 8.
(Hint: Use Simultaneous Assignments
Answer: a,b = b,a    Done!!
What is Simultaneous Assignments in python ?
The combination of automatic packing and unpacking forms a technique known as simultaneous assignment.We explicitly assign a series of values to a series of identifiers, all of the expressions are evaluated on the right-hand side before assignment.
>>> x, y, z = 6, 2, 5   # x = 6, y = 2, z = 5
>>> x
6
>>>z
5
Note: Data packing: Series of comma-separated will be treated as a single tuple, even
if no enclosing parentheses are provided.
data = 10,1,23,45   # it is equivalent to (10,1,23,45), python provide missing ( ).
It can be used while returning multiple values from function/method.  - return x,y
Data unpacking : Python can automatically unpack a sequence, allowing one to assign a series of individual identifiers to the elements of sequence.
Example :   a, b, c, d = range(7, 11)   # a=7, b=8, c=9, and d=10
It is used in built-in function, divmod(a, b), returns the pair of values (a // b, a % b) as quotient, remainder. quotient, remainder = divmod(a, b)
It can be used while iterating over sequence
for x, y in [ (7, 2), (5, 8), (6, 4) ]:   # x= 2, y = 7 in first iteration
for k, v in mapping.items():            #k - key of first dict entry and v = value

4.What is significance of  if name == __main__: in python module creation ?
Answer: In python module (a file with .py extension) is collection of functions and classes.There are various in built module for specific use included in python. Example : math for Mathematical operation , os for Operating system related thing, re for regular expression , sys for interaction with the Python interpreter, collection, array, etc.
We can create our custom module and it can be imported in python program or another module or executed as standalone program too. When a module is imported for the first time, the main block in that module is run. 
Every module has __name__  and value of __name__ is decided whether module has been used as standalone program or imported in a module.
  • If the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". 
  • If this file is being imported from another module, __name__ will be set to the module's name.
"if name == __main__:"  is a conditional statement used to distinguish whether given module is used as standalone program or as module. Consider following sample code and save it in a file named _module.py
if __name__ == '__main__':
     print 'This program is being run by itself'
 else:
     print 'I am being imported from another module'
Open this file in IDLE interpreter and execute it as standalone program it display "This program is being run by itself" because __name__ is initialized with value __main__ and that makes if condition true.
Now import it as module and press enter , it displays "I am being imported from another module"
>>> import _module
I am being imported from another module

Refer this for another example for better understanding.This approach used to embed unit tests within the module and execute as standalone program to test that module.

5.What is Deep and shallow copy in python ?
Answer: In python when an identifier is assigned a data structure, that identifier becomes an alias of that data structure. Either of identifier old or new referring to list can modify that data structure.
Suppose we want to create separate list for both identifier, python comes with concept of shallow copy and create a separate list for each.
list_original = ["Apple","mango","Water melon"]
copy_original_list =  list(list_original ) #list constructor used to create separate list DS. 55555555
>>> list_original = ["Apple","mango","Water melon"]
>>> copy_original_list = list_original [:]
Since python’s lists are referential and each element referenced by list can be a object(a sub-list), so when element of an list is an object then also we have not achieved clear separation of concern.
Here python come up with concept of deep copy, where copy method is executed recursively and all object is created separately for both references .
from copy import deepcopy
list_original  = ["Apple","mango","Water melon",["pineapple","papaya"]]
copy_original_list = deepcopy(list_original  )
copy_original_list[2][1] = "Jack fruit"
list_original  [0] = "No Fruit";

print copy_original_list  #['Apple', 'mango', 'Water melon', ['pineapple', 'jack fruit']]
print list_original  # ['No Fruit', 'mango', 'Water melon', ['pineapple', 'papaya']
For detail discussion about shallow and deep copy with example refer this.


Read about :  Python - object oriented paradigm
                      Python data structure



Location: Hyderabad, Telangana, India