Some python notes for pre-interview revision
Range vs Xrange
xrange is a sequence object that evaluates lazily. range creates a list, so if you do range(1, 10000000) it creates a list in memory with 10000000 elements. xrange is a generator, so it is a sequence object is a that evaluates lazily.
Tuple
- Immutable
- s = ("a","b","c") #paranthesis are optional
- Indexing support just like lists
- print(1,2,3) #prints 3 numbers
- print((1,2,3)) #prints a tuple
- a = () #empty tuple
- a = (2,) #singleton tuple
- a,b =
interprets the result of the expression as a tuple with two values. - a,b = b,a #swaps the variables
- a,b = [1,2] #obvious
- a,b = [1,2,3] #ValueError : Too many values to unpack
- a,*b = [1,2,3] #a=1 and b=[2,3]
Dictionary
- A hash map, key value pairs, is unordered.
- Keys must be unique and only consist of immutable objects like strings
Sequences
- Lists, strings and tuples are example of sequences.
- Supports "Membership Tests" : (for i in arr, for i not in arr)
- Supports Indexing Operations and Slicing
Set
- Unordered collection of simple objects
- Supports test for membership
References
- arr = [1,2,3]
- arr2 = arr
- arr3 = arr[:] #this makes a copy by full slicing
- del arr[0]
- print arr2 #[2,3]
- print arr3 #[1,2,3]
- Explaination: Assigning a variabel name to another variable name just makes creates a reference to the original object. If you want to make a completely new object and not just a reference then you have to use copy.
Object Oriented Programming
Definitions
- Objects that belong to the class or the instance of the class are called fields.
- Objects that belong to the class are called class variables and objects that belong to the instance of the class are called instance variables.
Self
- Python equivalent of this pointer in C++ or this reference in java and C#.
- The name self can be changed to something else also, although its not recommended you do that.
- Self is used to create a reference to the object being created of the class, so a call like 'myobject.method(arg1,arg2)' gets internally inflated as 'MyClass.method(myobject,arg1,arg2)'
@staticmethod decorator
- Those methods which belong exclusively to the class and not its instances
Implementing Inheritance
- class SchoolMember():...
- class Teacher(SchoolMember):...
Special Methods in Classes
- __inti__(self, ...) : Called right before the newly created object is returned for usage.
- __del__(self) : Called just before the object is destroyed.
- __str__(self) : Called when we use the print function of when str() is used.
- __lt__(self,other) : called when less than operator is used (<), Similarly there are methods for all the operators (+,>,- etc)
- __getitem__(self,key): Called when x[key] indexing call is made.
- __len__(self) : Called when the built-in len() function is used for sequence object.
Exceptions
- Else: this block is executed in the case everything is fine and no exceptions occur.
- Finally: this block is executed when all the exception cases are met and the interpreter is about to exit the try block
User defined Exception Class
class ShortInputException():
def __init__(self,length,atleast):
Exception.__init__(self):
self.length = length
self.atleast = atleast
#Now lets raise this exception
if len(text) < 3: raise ShortInputException(len(text),3)
Lambda Expression
- A lambda statement is used to create new function objects.
points = [{'x':2,'y':30},{'x':1,'y':9}]
points.sort(key=lambda i : i['y'])
[{’x’: 1, ’y’: 9}, {’x’: 2, ’y’: 30}]
Recieving tuples and dictionaries of indefinite lengths in functions
oints.sort(key=lambda i : i['y'])
def sum(*args):
''' Returns the sume of all the parameters '''
return sum(a)
sum(1,43,54,7,8)
>>> 113
Because we have a * prefix on the args variable, all extra arguments passed to the function are stored in args as a tuple. If a ** prefix had been used instead, the extra parameters would be considered to be key/value pairs of a dictionary.
The Assert Statement
def sum(a,b):
assert type(a) == int
assert type(b) == int
return sum(a,b)