Tuesday, 7 April 2015

Python Notes

Some python notes for pre-interview revision


  • 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]


  • A hash map, key value pairs, is unordered.
  • Keys must be unique and only consist of immutable objects like strings


  • 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


  • Unordered collection of simple objects
  • Supports test for membership


  • 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


  • 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.


  • 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.


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

Tuesday, 31 March 2015

How to remove a package in ubuntu when you don't know its name ?

So I had this ubuntu alarm clock app installed, which I wanted to remove, but I couldn't find its package name.

So here is the command to figure out the package name of an installed app 

dpkg --get-selections | grep 

And woot, I've found it. Now lets get rid of it.

sudo apt-get purge alarm-clock-applet

Ideas and Memory tradeoff

I have a hypothesis that there exists a tradeoff in the mind between the tendency to think big,bright ideas and being able to recall them later.

Explaining this further, the brighter and more revolutionary the idea you just thought of, the lesser are the chances that you will be able to recall it by the time you decide to work on it.

But with maturity and practice, this tradeoff must fade off, that's why people who are in the profession of implementing ideas liek artists, writers, musicians produce the best work of their lives after much much practice.

To cite a famous example, Douglas Adams, once was presumably high and was having a lunch conversation with his friend, during this conversation, Adams told him three ideas, one of them was the book “The Hitchhiker’s guide to the galaxy”. 
They realised the importance of these ideas and knew instantly that they were profound.

When they met later, they forgot the two ideas except for the "Hitchhiker's guide to the galaxy" one.
None of them was able to figure out, what the rest of the ideas were, except for the fact that they were equally revolutionary.

Now imagine what the other two ideas might have been.

Source : A documentary titled "Life, Universe and Doughlas Adams" https://www.youtube.com/watch?v=OHJLNrDzYm0

On Observation

When an astronomer looks up in his little telescope and locates a galaxy amidst the white dust, he wonders whether this galaxy existed before he decided to observe it.

A tree falls in the forest far away, away from any human or mammal, does it make noise, even when there is no one to hear it ?

Well no, it doesn't make any noise, because noise is the result of vibrations in the air coming in contact with eardrums in mammals, so for there to be noise, there must be someone to observe it.

So just like a tree falling in a forest far far away doesn’t make any noise similarly does things that no one observe, like some very distant, very faintly visible galaxy, does they exist ?

Space and Time

Space and Time

This post is a transcription of Alan Watts philosophy along with some gems from the armchair philosopher in me.

The perception of space and time we have today is very limited (I am specifically talking of layman here, physicists and philosophers and other learned men do indeed have a better view).

We view time as a linear function and space as finite, discrete and omnipresent.

What Alan Watts says is that, this is just one way of looking at things, and no one way is right. But sometimes we must be exposed with other point of views to really get an idea of “what’s going on”.

Lets talk about space first, If I ask you to describe “the sun” for me, you would go about it like, its a sphere of so and so diameter, and so and so location.

Here we are using matter as distinction between the space where sun ends and emptiness begins.

But we also know that there is significant equivalence between matter and waves, so if I were to use EM waves instead of matter in defining the boundary points of the sun, I would still be technically correct.

But by that definition, we are inside the sun, in fact all the portion that the first rays of sun has reached is all inside the sun.

So you see, its all a matter of definition, how we define  things is how we end up looking at them.

Now lets talk about time,


Chicken and Egg

This post is a transcription of one of Alan Watts philosophy.(the idea might date way back to the medival ages, but I heard it first in one of Alan Watts lectures.)

Everything is reproduction, every event, in one way or another.

An egg is a chicken’s way of becoming another chicken.

A planet is a star’s way of becoming another star.

And intelligence is a disease, that makes that planet into a star.

And in a way, life is a planet's way of becoming a star. 
Explaination : Life evolves into higher forms of intelligence, they find about nuclear fission and fusion, and end up blowing the planet to pieces, starring it up ?

And just like during mammal reproduction, of all the sperm cells, only one or two succeeds in making an egg, similarly out of all the planets that might be part of a star’s solar system, only one or two would sustain life, the life enables one of the species in attaining complete control over that planet, and then that species finally learns how to blow up the planet to pieces, and then its only a matter of time.

I would like to go further and say that, this analogy of reproduction can be used to explain almost all of the significant events.

An execution in an Idea’s way of becoming another idea.

and finally conclude by saying,

Death is one Life’s way of becoming another life.

I need to drink some coffee to get hold of these dense ideas.