In [ ]:
# range(start, stop[, step]) The arguments must be plain integers
result = range(10)
print(result)
print(range(10, 20, 2))
In [ ]:
print(type(result)) # it return list type. We will talk about it later. it is just sequence of items
print(type(result[0]))
In [ ]:
# in general to see the syntax use ? or ??. ipython or jupyter notebook support tab completion
range?
In [ ]:
# you can press <Shift>-<Tab> to get a tooltip showing the function's signature in notebook
In [ ]:
#for <variable> in <sequence>:
#<statements>
for item in range(10):
print('item {} item square {}'.format(item, item*item))
In [ ]:
x = [1, 3, 5, 10]
print(x[0]) # list is 0 index based
print(x[3])
list support append, insert and remove
In [ ]:
y = list() # same as y = [], syntactic sugar
y.append('red')
y.append(10) # it is heterogenuous collection of item
print(y)
Via list comphrehension
In [ ]:
# [<some_func>(x) for x in <something> if <some_condition_is_true>]
square_list = [x*x for x in range(10)]
print(square_list)
In [ ]:
even_number_square_list = [x*x for x in range(10) if x%2 ==0]
print(even_number_square_list)
In [ ]:
our_galaxy = ("Milky Way ", "100,000-120,000", 200, 100) # name, diameter, stars, planets
print(our_galaxy)
print(our_galaxy[0])
tuple unpacking
In [ ]:
name, diameter, stars, planets = our_galaxy # tuple unpacking
print(planets)
One of the major disadvantage is their readability. What is the third poition of a tuple. Can guess from context, but is hard in general if there are lot element in tuple.
Name tuple come to rescue in this situation. no covering in this workshope
creating dictionaries
In [ ]:
algoConfig = {} # can use nameAgeDic = dict()
algoConfig['threshold'] = 20 # in pixel
algoConfig['neighborhoodSize'] = 4 # 4X4 neighborhood
algoConfig['tolerance'] = 0.002 # convergence tolerance
print(algoConfig)
some syntactic sugar
In [ ]:
charValDict = {'a':2, 'b': 10, 'c':54}
print charValDict
print charValDict['b']
All the keys and values in dictionaries
In [ ]:
print(charValDict.keys())
print(charValDict.values())
print(charValDict.items())
Using directionary comprehension
In [ ]:
studentScore = [['John', (10, 20 )], ['sam', (30, 50)] , ['paul', (40, 20)]]
finalScoreDict = { name: sum(score) for name, score in studentScore }
print(finalScoreDict)
In [ ]:
nameSet = set() # empty set
ageSet = set([10, 20, 5])
print(ageSet)
ageSet.add(15)
print('set after adding {} is {}'.format(15, ageSet))
print('Cardinality of set is {}'.format(len(ageSet))) #cardinality of set
10 in ageSet # membership
Excercise: Supose we have following dictioney of instructor name: course taught What are the different course taught in the department?
In [ ]:
instructorCourseLibrary = {'Dr. Mohammad Mahoor': ['Machine learning', 'VLSI Design', 'linear lagebra'],
'Dr. KIMON VALAVANIS':[ 'Pattern Recognition', 'statistics'] ,
'Dr. GEORGE EDWARDS':['VLSI Design', 'Pattern Recognition'] }
In [ ]:
def calculate_l2_norm_square_of_vector(vec):
sum = 0
for item in vec:
sum = sum + item*item
return sum
In [ ]:
print(calculate_l2_norm_square_of_vector([1,2]))
In [ ]:
def logInfo(level, *args ):
print level
print args
for arg in args:
print(arg)
logInfo(1, '9 Nov', 'Denver', 75 )
Actually these variable number of arguments are packed into a tuple.
Using *operator we can do the opposite i.e unpack the argument out of a list or tuple
Similary for passing variable length keyword argument use following syntax
In [ ]:
def logInfoKeyWord(level, **kwargs ):
print level
print kwargs
for key , val in kwargs.items():
print('key = {} value = {}'.format(key, val))
logInfoKeyWord(1, Date= '9 Nov', City = 'Denver', Temperature=75)
Or we can use ** operator on a dictionary to get keyword arguments
In [ ]:
params = {'Date': '9 Nov', 'City' : 'Houston', 'Temperature':75}
logInfoKeyWord(1, **params )
Before the variable number of arguments, zero or more normal arguments may occur. if we use both then *args must occur before **kwargs
Python comes some built in function like print, len etc and a set of modules called standard library. A module is set of related python function like math, random, numpy, scipy, matplotlib etc. To use a module you has to first import it using one of following syntax.
In [ ]:
import math
math.sin(math.pi/2)
or
In [ ]:
import math as mt
mt.sin(mt.pi/2)
In [ ]:
from math import sin, pi
sin(pi/2)
In [ ]:
import numpy as np
x = np.array([[1, 4 ,8],[ 3 , 4, 6]])
print(x)
slicing numpy array is similar to MATLAB
In [ ]:
print(x[1,1:])
In [ ]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10)
line, = plt.plot(x, np.sin(x), '--', linewidth=2)
plt.show()
Most of the the scientifc work is driven by numpy, scipy,sympy, matplotlib, bokeh, pandas and
domain specific packages like
image processing scikit-image: Image processing in Python — scikit-image
Just google and there will be a package for the job.
Checkout repository of software for the Python https://pypi.python.org/pypi