Python

Sorting a list of tuples by multiple conditions:

sorted_by_length = sorted(list_,
                         key=lambda x: (x[0], len(x[1]), float(x[1])))

To get the lower bound integer in python:

int(1.6) =1

int(1.4)=1


function:

def function_name(i):


Modules:

write a python file with filename.py extension and add definitions and statements in them.

‘import filename’ in another file.

access definitions inside that file using filename.nameofdef


tup=()

concatenating to a tuple: tup=tup+(a[i],)

list1=[] – ordered sequence.

list1.append(1)

Can’t mutate a string. assignment error.


Aliasing problem in python:

if you have an object say a list and you attach it to the name list1

if you say list2=list1

list2=list1, then list2 points to same object as that of list one.

If you add an element to list2, then it will be reflected in list1 as well which you might not have intended.

So how to take a copy of list1 without having any impact on list1 if I do changes to the copy?

list2=list1[:]              cloned

sort the original list-> list1.sort()

take a sorted list of original list into another object

list2=sorted(list1)

http://stackoverflow.com/q/2739552/5819704 – [[1,2]]*3, all three lists inside outer list refer to same object. This doesn’t sync with your intuition at the beginning.

tuple and string doesn’t support item assignment i.e. s[1]=5, only list supports.


Functions as objects:

sending functions as arguments to other functions.

Higher order programming: Map

Dictionaries: A list of key, value pairs

my_dict={‘Ana’:’B’,”Vivek’:’Ex’}

‘Vivek’ in my_dict  -> True

my_dict[‘Vivek’]=’Ex’

my_dict.keys{}

my_dict.values{}

Memorization: Storing the already computed values in dictionary and looking up for them in case we need them again. This will save from computing something that is already computed.


Debugging:

  1. Testing:
    1. Unit testing-
      1. validate each piece of the program.
      2. testing each function separately.
    2. Regression testing-
      1. After each fix, you need to retest to confirm already tested modules or not broken by the latest fix.
    3. Integration testing-
      1. Does overall program work?
    4. Black box testing-
      1. without looking at the code.
      2. done by other than the implementer to avoid some implementer biases.
    5. Glass box testing:
      1. Path complete.
      2. Design of test cases based on code.
  2. Defensive programming:
    1. specifications for functions.
    2. Modularize programs.
    3. check conditions on inputs/outputs.
  3. Eliminate the source of bugs:

try:

except:

else:

finally:

raise ()

assert             to check whether the assumptions are met or not.


classes and objects:

Data attributes associated with the class, but not with instance or objects.

Generator: yield 1 in method. runs upto the yield and stops. again call the funct.__next__() runs upto next yield and stops.


Lisp and python programming languages allow you to implement reflection.


Using Pylab:

import pylab as plt

plt.figure(‘figurename’) – to plot in new figure

plt.clf()

plt.ylim(0,1000)

plt.title(‘Linear’)

plt.xlabel(‘sample points’)

plt.ylabel(‘linear function’)

plt.subplot(211)

plt.plot(list of x values, list of y values,’b-‘,label=’linear’)

plt.yscale(‘log’)

model=pylab.polyfit(observedX,observedY, n)

Finds coefficients of a polynomial of degree n, that provides a best least squares fit for the observed data. It returns n+1 values.

estYvalues=pylab.polyval(model,xVals)

 


Anonymous function – lambda:

f1=lambda x,y: x+y

f1(2,3)=5


Credits: Jake Vanderplas

An abstract class in python can’t be instantiated.


Scikit:


Pandas:


using both 2.7 and 3.5 of python in diferent environments:

It won’t act weird if you will do it in tensor flow environment. Please follow these steps:
Install python 3.5

you can do the following to use python 3.5 on the new conda environnement “tensorflow”:

conda create –name tensorflow python=3.5
activate tensorflow
conda install jupyter
conda install scipy
pip install tensorflow
or
pip install tensorflow-gpu

You can uninstall python 2.7 also, but if you will follow above steps you can keep python 2.7 and python 3.5 also. They wont act weird. So in this case for anaconda by default it would be python 2.7. But for tensorflow environment it will work on python 3.5


view models of keras

import os
os.environ[“PATH”] += os.pathsep + ‘C:/Anaconda2/envs/tensorflow/Library/bin/graphviz’

from keras.utils.vis_utils import plot_model
plot_model(model, to_file=’model.png’)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s