diff options
-rw-r--r-- | advanced_python/slides/arrays.tex | 177 | ||||
-rw-r--r-- | advanced_python/slides/modules.tex | 27 | ||||
-rw-r--r-- | advanced_python/slides/plotting.tex | 152 | ||||
-rw-r--r-- | basic_python/slides/func.tex | 222 | ||||
-rw-r--r-- | basic_python/slides/io_files_parsing.tex | 112 | ||||
-rw-r--r-- | basic_python/slides/strings_loops_lists.tex | 244 | ||||
-rw-r--r-- | basic_python/slides/tuples_dicts_sets.tex | 118 |
7 files changed, 560 insertions, 492 deletions
diff --git a/advanced_python/slides/arrays.tex b/advanced_python/slides/arrays.tex index 7b829f9..b565e72 100644 --- a/advanced_python/slides/arrays.tex +++ b/advanced_python/slides/arrays.tex @@ -7,9 +7,9 @@ \item Much faster than arrays \end{itemize} \begin{lstlisting} - a1 = array([1,2,3,4]) + In []: a1 = array([1,2,3,4]) a1 # 1-D - a2 = array([[1,2,3,4],[5,6,7,8]]) + In []: a2 = array([[1,2,3,4],[5,6,7,8]]) a2 # 2-D \end{lstlisting} \end{frame} @@ -17,39 +17,38 @@ \begin{frame}[fragile] \frametitle{\texttt{arange} and \texttt{shape}} \begin{lstlisting} - ar1 = arange(1, 5) - - ar2 = arange(1, 9) - print ar2 - ar2.shape = 2, 4 - print ar2 + In []: ar1 = arange(1, 5) + In []: ar2 = arange(1, 9) + In []: print ar2 + In []: ar2.shape = 2, 4 + In []: print ar2 \end{lstlisting} \begin{itemize} \item \texttt{linspace} and \texttt{loadtxt} also returned arrays \end{itemize} \begin{lstlisting} - ar1.shape - ar2.shape + In []: ar1.shape + In []: ar2.shape \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{Special methods} \begin{lstlisting} - identity(3) + In []: identity(3) \end{lstlisting} \begin{itemize} \item array of shape (3, 3) with diagonals as 1s, rest 0s \end{itemize} \begin{lstlisting} - zeros((4,5)) + In []: zeros((4,5)) \end{lstlisting} \begin{itemize} \item array of shape (4, 5) with all 0s \end{itemize} \begin{lstlisting} - a = zeros_like([1.5, 1, 2, 3]) - print a, a.dtype + In []: a = zeros_like([1.5, 1, 2, 3]) + In []: print a, a.dtype \end{lstlisting} \begin{itemize} \item An array with all 0s, with similar shape and dtype as argument @@ -61,17 +60,17 @@ \begin{frame}[fragile] \frametitle{Operations on arrays} \begin{lstlisting} - a1 - a1 * 2 - a1 + In []: a1 + In []: a1 * 2 + In []: a1 \end{lstlisting} \begin{itemize} \item The array is not changed; New array is returned \end{itemize} \begin{lstlisting} - a1 + 3 - a1 - 7 - a1 / 2.0 + In []: a1 + 3 + In []: a1 - 7 + In []: a1 / 2.0 \end{lstlisting} \end{frame} @@ -81,25 +80,25 @@ \item Like lists, we can assign the new array, the old name \end{itemize} \begin{lstlisting} - a1 = a1 + 2 - a1 + In []: a1 = a1 + 2 + In []: a1 \end{lstlisting} \begin{itemize} \item \alert{Beware of Augmented assignment!} \end{itemize} \begin{lstlisting} - a, b = arange(1, 5), arange(1, 5) - print a, a.dtype, b, b.dtype - a = a/2.0 - b /= 2.0 - print a, a.dtype, b, b.dtype + In []: a, b = arange(1, 5), arange(1, 5) + In []: print a, a.dtype, b, b.dtype + In []: a = a/2.0 + In []: b /= 2.0 + In []: print a, a.dtype, b, b.dtype \end{lstlisting} \begin{itemize} \item Operations on two arrays; element-wise \end{itemize} \begin{lstlisting} - a1 + a1 - a1 * a2 + In []: a1 + a1 + In []: a1 * a2 \end{lstlisting} \end{frame} @@ -108,24 +107,24 @@ \begin{frame}[fragile] \frametitle{Accessing \& changing elements} \begin{lstlisting} - A = array([12, 23, 34, 45, 56]) + In []: A = array([12, 23, 34, 45, 56]) - C = array([[11, 12, 13, 14, 15], + In []: C = array([[11, 12, 13, 14, 15], [21, 22, 23, 24, 25], [31, 32, 33, 34, 35], [41, 42, 43, 44, 45], [51, 52, 53, 54, 55]]) - A[2] - C[2, 3] + In []: A[2] + In []: C[2, 3] \end{lstlisting} \begin{itemize} \item Indexing starts from 0 \item Assign new values, to change elements \end{itemize} \begin{lstlisting} - A[2] = -34 - C[2, 3] = -34 + In []: A[2] = -34 + In []: C[2, 3] = -34 \end{lstlisting} \end{frame} @@ -135,49 +134,49 @@ \item Indexing works just like with lists \end{itemize} \begin{lstlisting} - C[2] - C[4] - C[-1] + In []: C[2] + In []: C[4] + In []: C[-1] \end{lstlisting} \begin{itemize} \item Change the last row into all zeros \end{itemize} \begin{lstlisting} - C[-1] = [0, 0, 0, 0, 0] + In []: C[-1] = [0, 0, 0, 0, 0] \end{lstlisting} OR \begin{lstlisting} - C[-1] = 0 + In []: C[-1] = 0 \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{Accessing columns} \begin{lstlisting} - C[:, 2] - C[:, 4] - C[:, -1] + In []: C[:, 2] + In []: C[:, 4] + In []: C[:, -1] \end{lstlisting} \begin{itemize} \item The first parameter is replaced by a \texttt{:} to specify we require all elements of that dimension \end{itemize} \begin{lstlisting} - C[:, -1] = 0 + In []: C[:, -1] = 0 \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{Slicing} \begin{lstlisting} - I = imread('squares.png') - imshow(I) + In []: I = imread('squares.png') + In []: imshow(I) \end{lstlisting} \begin{itemize} \item The image is just an array \end{itemize} \begin{lstlisting} - print I, I.shape + In []: print I, I.shape \end{lstlisting} \begin{enumerate} \item Get the top left quadrant of the image @@ -191,14 +190,14 @@ \item Slicing works just like with lists \end{itemize} \begin{lstlisting} - C[0:3, 2] - C[2, 0:3] - C[2, :3] + In []:C[0:3, 2] + In []: C[2, 0:3] + In []:C[2, :3] \end{lstlisting} \begin{lstlisting} - imshow(I[:150, :150]) + In []: imshow(I[:150, :150]) - imshow(I[75:225, 75:225]) + In []: imshow(I[75:225, 75:225]) \end{lstlisting} \end{frame} @@ -211,15 +210,15 @@ \item The idea is similar to striding in lists \end{itemize} \begin{lstlisting} - C[0:5:2, 0:5:2] - C[::2, ::2] - C[1::2, ::2] + In []: C[0:5:2, 0:5:2] + In []: C[::2, ::2] + In []: C[1::2, ::2] \end{lstlisting} \begin{itemize} \item Now, the image can be shrunk by \end{itemize} \begin{lstlisting} - imshow(I[::2, ::2]) + In []: imshow(I[::2, ::2]) \end{lstlisting} \end{frame} @@ -252,13 +251,28 @@ \begin{frame}[fragile] \frametitle{Least Square Fit} \begin{lstlisting} - l, t = loadtxt("pendulum.txt", unpack=True) - l - t - tsq = t * t - plot(l, tsq, 'bo') - plot(l, tsq, 'r') - \end{lstlisting} + In []: L, t = loadtxt("pendulum.txt", + unpack=True) + In []: L + In []: t + In []: tsq = t * t + In []: plot(L, tsq, 'bo') +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] +\frametitle{$L$ vs. $T^2$ - Scatter} +Linear trend visible. +\begin{figure} +\includegraphics[width=4in]{data/L-Tsq-points} +\end{figure} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Least Square Fit} +\begin{lstlisting} + In []: plot(L, tsq, 'r') +\end{lstlisting} \begin{itemize} \item Both the plots, aren't what we expect -- linear plot \item Enter Least square fit! @@ -266,6 +280,23 @@ \end{frame} \begin{frame}[fragile] +\frametitle{$L$ vs. $T^2$ - Line} +This line does not make any mathematical sense. +\vspace{-0.1in} +\begin{figure} +\includegraphics[width=4in]{data/L-Tsq-Line} +\end{figure} +\end{frame} + +\begin{frame}[fragile] +\frametitle{$L$ vs. $T^2$ - Least Square Fit} +This is what our intention is. +\begin{figure} +\includegraphics[width=4in]{data/least-sq-fit} +\end{figure} +\end{frame} + +\begin{frame}[fragile] \frametitle{Matrix Formulation} \begin{itemize} \item We need to fit a line through points for the equation $T^2 = m \cdot L+c$ @@ -295,34 +326,36 @@ \begin{frame}[fragile] \frametitle{Least Square Fit Line} \begin{lstlisting} - A = array((l, ones_like(l))) - A.T - A + In []: A = array((L, ones_like(L))) + In []: A = A.T + In []: A \end{lstlisting} \begin{itemize} \item We now have \texttt{A} and \texttt{tsq} \end{itemize} \begin{lstlisting} - result = lstsq(A, tsq) + In []: result = lstsq(A, tsq) \end{lstlisting} \begin{itemize} \item Result has a lot of values along with m and c, that we need \end{itemize} \begin{lstlisting} - m, c = result[0] - print m, c + In []: m, c = result[0] + In []: print m, c \end{lstlisting} \end{frame} + + \begin{frame}[fragile] \frametitle{Least Square Fit Line} \begin{itemize} \item Now that we have m and c, we use them to generate line and plot \end{itemize} \begin{lstlisting} - tsq_fit = m * l + c - plot(l, tsq, 'bo') - plot(l, tsq_fit, 'r') + In []: tsq_fit = m * L + c + In []: plot(L, tsq, 'bo') + In []:plot(L, tsq_fit, 'r') \end{lstlisting} \end{frame} diff --git a/advanced_python/slides/modules.tex b/advanced_python/slides/modules.tex index 957789a..edae339 100644 --- a/advanced_python/slides/modules.tex +++ b/advanced_python/slides/modules.tex @@ -6,13 +6,13 @@ \item Script to print `hello world' -- \texttt{hello.py} \end{itemize} \begin{lstlisting} - print "Hello world!" + In []: print "Hello world!" \end{lstlisting} \begin{itemize} \item We have been running scripts from IPython \end{itemize} \begin{lstlisting} - %run -i hello.py + In []: %run -i hello.py \end{lstlisting} \begin{itemize} \item Now, we run from the shell using python @@ -28,9 +28,9 @@ \item Save the following in \texttt{sine\_plot.py} \end{itemize} \begin{lstlisting} - x = linspace(-2*pi, 2*pi, 100) - plot(x, sin(x)) - show() + In []: x = linspace(-2*pi, 2*pi, 100) + In []: plot(x, sin(x)) + In []: show() \end{lstlisting} \begin{itemize} \item Now, let us run the script @@ -103,19 +103,20 @@ \item Save it as \texttt{gcd\_script.py} \end{itemize} \begin{lstlisting} - def gcd(a, b): - while b: - a, b = b, a%b - return a + In []: def gcd(a, b): + .... while b: + .... a, b = b, a%b + .... return a + .... \end{lstlisting} \begin{itemize} \item Also add the tests to the file \end{itemize} \begin{lstlisting} - if gcd(40, 12) == 4 and gcd(12, 13) == 1: - print "Everything OK" - else: - print "The GCD function is wrong" + .... if gcd(40, 12) == 4 and gcd(12, 13) == 1: + .... print "Everything OK" + .... else: + .... print "The GCD function is wrong" \end{lstlisting} \begin{lstlisting} $ python gcd_script.py diff --git a/advanced_python/slides/plotting.tex b/advanced_python/slides/plotting.tex index 4f8d51f..6fa31e6 100644 --- a/advanced_python/slides/plotting.tex +++ b/advanced_python/slides/plotting.tex @@ -9,8 +9,8 @@ $ ipython -pylab \end{lstlisting} % $ \begin{lstlisting} - p = linspace(-pi,pi,100) - plot(p, cos(p)) + In []: p = linspace(-pi,pi,100) + In []: plot(p, cos(p)) \end{lstlisting} \end{frame} @@ -20,11 +20,11 @@ \begin{itemize} \item \texttt{p} has a hundred points in the range -pi to pi \begin{lstlisting} - print p[0], p[-1], len(p) + In []: print p[0], p[-1], len(p) \end{lstlisting} \item Look at the doc-string of \texttt{linspace} for more details \begin{lstlisting} - linspace? + In []: linspace? \end{lstlisting} \end{itemize} \begin{itemize} @@ -38,50 +38,50 @@ \begin{frame}[fragile] \frametitle{Plot color and thickness} \begin{lstlisting} - clf() - plot(p, sin(p), 'r') + In []: clf() + In []: plot(p, sin(p), 'r') \end{lstlisting} \begin{itemize} \item Gives a sine curve in Red. \end{itemize} \begin{lstlisting} - plot(p, cos(p), linewidth=2) + In []: plot(p, cos(p), linewidth=2) \end{lstlisting} \begin{itemize} \item Sets line thickness to 2 \end{itemize} \begin{lstlisting} - clf() - plot(p, sin(p), '.') + In []: clf() + In []:plot(p, sin(p), '.') \end{lstlisting} \begin{itemize} \item Produces a plot with only points \end{itemize} \begin{lstlisting} - plot? + In []: plot? \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{\texttt{title}} \begin{lstlisting} - x = linspace(-2, 4, 50) - plot(x, -x*x + 4*x - 5, 'r', linewidth=2) - title("Parabolic function -x^2+4x-5") + In []: x = linspace(-2, 4, 50) + In []: plot(x, -x*x + 4*x - 5, 'r', linewidth=2) + In []: title("Parabolic function -x^2+4x-5") \end{lstlisting} \begin{itemize} \item We can set title using \LaTeX~ \end{itemize} \begin{lstlisting} - title("Parabolic function $-x^2+4x-5$") + In []: title("Parabolic function $-x^2+4x-5$") \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{Axes labels} \begin{lstlisting} - xlabel("x") - ylabel("f(x)") + In []: xlabel("x") + In []:ylabel("f(x)") \end{lstlisting} \begin{itemize} \item We could, if required use \LaTeX~ @@ -91,7 +91,7 @@ \begin{frame}[fragile] \frametitle{Annotate} \begin{lstlisting} - annotate("local maxima", xy=(2, -1)) + In []: annotate("local maxima", xy=(2, -1)) \end{lstlisting} \begin{itemize} \item First argument is the annotation text @@ -103,8 +103,8 @@ \begin{frame}[fragile] \frametitle{Limits of Plot area} \begin{lstlisting} - xlim() - ylim() + In []: xlim() + In []: ylim() \end{lstlisting} \begin{itemize} \item With no arguments, \texttt{xlim} \& \texttt{ylim} get the @@ -112,10 +112,10 @@ \item New limits are set, when arguments are passed to them \end{itemize} \begin{lstlisting} - xlim(-4, 5) + In []: xlim(-4, 5) \end{lstlisting} \begin{lstlisting} - ylim(-15, 2) + In []: ylim(-15, 2) \end{lstlisting} \end{frame} @@ -126,17 +126,17 @@ \begin{itemize} \item To see the history of commands, we typed \begin{lstlisting} - %hist + In []: %hist \end{lstlisting} \item All commands, valid or invalid, appear in the history \item \texttt{\%hist} is a magic command, available only in IPython \end{itemize} \begin{lstlisting} - %hist 5 + In []: %hist 5 # last 5 commands \end{lstlisting} \begin{lstlisting} - %hist 5-10 + In []: %hist 5-10 # commands between 5 and 10 \end{lstlisting} \end{frame} @@ -150,7 +150,7 @@ \item \texttt{\%save} magic command to save the commands to a file \end{itemize} \begin{lstlisting} - %save plot_script.py 1 3-6 8 + In []: %save plot_script.py 1 3-6 8 \end{lstlisting} \begin{itemize} \item File name must have a \texttt{.py} extension @@ -160,7 +160,7 @@ \begin{frame}[fragile] \frametitle{Running the script} \begin{lstlisting} - %run -i plot_script.py + In []: %run -i plot_script.py \end{lstlisting} \begin{itemize} \item There were no errors in the plot, but we don't see it! @@ -168,7 +168,7 @@ \item We need to explicitly ask for the image to be shown \end{itemize} \begin{lstlisting} - show() + In []: show() \end{lstlisting} \begin{itemize} \item \texttt{-i} asks the interpreter to check for names, @@ -183,9 +183,9 @@ \begin{frame}[fragile] \frametitle{\texttt{savefig}} \begin{lstlisting} - x = linspace(-3*pi,3*pi,100) - plot(x,sin(x)) - savefig('sine.png') + In []: x = linspace(-3*pi,3*pi,100) + In []: plot(x,sin(x)) + In []: savefig('sine.png') \end{lstlisting} \begin{itemize} \item \texttt{savefig} takes one argument @@ -199,16 +199,16 @@ \begin{frame}[fragile] \frametitle{Overlaid plots} \begin{lstlisting} - x = linspace(0, 50, 10) - plot(x, sin(x)) + In []: x = linspace(0, 50, 10) + In []: plot(x, sin(x)) \end{lstlisting} \begin{itemize} \item The curve isn't as smooth as we expected \item We chose too few points in the interval \end{itemize} \begin{lstlisting} - y = linspace(0, 50, 500) - plot(y, sin(y)) + In []: y = linspace(0, 50, 500) + In []: plot(y, sin(y)) \end{lstlisting} \begin{itemize} \item The plots are overlaid @@ -219,14 +219,14 @@ \begin{frame}[fragile] \frametitle{Legend} \begin{lstlisting} - legend(['sine-10 points', 'sine-500 points']) + In []: legend(['sine-10 points', 'sine-500 points']) \end{lstlisting} \begin{itemize} \item Placed in the location, \texttt{pylab} thinks is `best' \item \texttt{loc} parameter allows to change the location \end{itemize} \begin{lstlisting} - legend(['sine-10 points', 'sine-500 points'], + In []: legend(['sine-10 points', 'sine-500 points'], loc='center') \end{lstlisting} \end{frame} @@ -234,24 +234,24 @@ \begin{frame}[fragile] \frametitle{Plotting in separate figures} \begin{lstlisting} - clf() - x = linspace(0, 50, 500) - figure(1) - plot(x, sin(x), 'b') - figure(2) - plot(x, cos(x), 'g') + In []: clf() + In []: x = linspace(0, 50, 500) + In []: figure(1) + In []: plot(x, sin(x), 'b') + In []:figure(2) + In []: plot(x, cos(x), 'g') \end{lstlisting} \begin{itemize} \item \texttt{figure} command allows us to have plots separately \item It is also used to switch context between the plots \end{itemize} \begin{lstlisting} - savefig('cosine.png') - figure(1) - title('sin(y)') - savefig('sine.png') - close() - close() + In []: savefig('cosine.png') + In []: figure(1) + In []: title('sin(y)') + In []: savefig('sine.png') + In []: close() + In []: close() \end{lstlisting} \begin{itemize} \item \texttt{close('all')} closes all the figures @@ -261,7 +261,7 @@ \begin{frame}[fragile] \frametitle{Subplots} \begin{lstlisting} - subplot(2, 1, 1) + In []: subplot(2, 1, 1) \end{lstlisting} \begin{itemize} \item number of rows @@ -269,13 +269,13 @@ \item plot number, in serial order, to access or create \end{itemize} \begin{lstlisting} - subplot(2, 1, 2) - x = linspace(0, 50, 500) - plot(x, cos(x)) + In []: subplot(2, 1, 2) + In []: x = linspace(0, 50, 500) + In []: plot(x, cos(x)) - subplot(2, 1, 1) - y = linspace(0, 5, 100) - plot(y, y ** 2) + In []: subplot(2, 1, 1) + In []: y = linspace(0, 5, 100) + In []: plot(y, y ** 2) \end{lstlisting} \end{frame} @@ -289,8 +289,8 @@ \item We read the data using \texttt{loadtxt} \end{itemize} \begin{lstlisting} - primes = loadtxt('primes.txt') - print primes + In []: primes = loadtxt('primes.txt') + In []: print primes \end{lstlisting} \begin{itemize} \item \texttt{primes} is a sequence of floats @@ -306,8 +306,8 @@ \item \texttt{loadtxt} requires both columns to be of same length \end{itemize} \begin{lstlisting} - pend = loadtxt('pendulum.txt') - print pend + In []: pend = loadtxt('pendulum.txt') + In []: print pend \end{lstlisting} \begin{itemize} \item \texttt{pend} is not a simple sequence like \texttt{primes} @@ -317,9 +317,9 @@ \begin{frame}[fragile] \frametitle{Unpacking with \texttt{loadtxt}} \begin{lstlisting} - L, T = loadtxt('pendulum.txt', unpack=True) - print L - print T + In []: L, T = loadtxt('pendulum.txt', unpack=True) + In []: print L + In []: print T \end{lstlisting} \begin{itemize} \item We wish to plot L vs. $T^2$ @@ -327,9 +327,9 @@ \item (We could instead iterate over T and calculate) \end{itemize} \begin{lstlisting} - Tsq = square(T) + In []: Tsq = square(T) - plot(L, Tsq, '.') + In []: plot(L, Tsq, '.') \end{lstlisting} \end{frame} @@ -341,11 +341,11 @@ \item Read the values and make an error bar plot \end{itemize} \begin{lstlisting} - L, T, L_err, T_err = \ - loadtxt('pendulum_error.txt', unpack=True) - Tsq = square(T) + In []: L, T, L_err, T_err = \ + In []: loadtxt('pendulum_error.txt', unpack=True) + In []: Tsq = square(T) - errorbar(L, Tsq , xerr=L_err, + In []: errorbar(L, Tsq , xerr=L_err, yerr=T_err, fmt='b.') \end{lstlisting} \end{frame} @@ -361,10 +361,10 @@ \item Let's plot the data of profits of a company \end{itemize} \begin{lstlisting} - year, profit = loadtxt('company-a-data.txt', + In []: year, profit = loadtxt('company-a-data.txt', dtype=type(int())) - scatter(year, profit) + In []: scatter(year, profit) \end{lstlisting} \begin{itemize} \item \alert{\texttt{dtype=int}; default is float} @@ -374,11 +374,11 @@ \begin{frame}[fragile] \frametitle{Pie Chart \& Bar Chart} \begin{lstlisting} - pie(profit, labels=year) + In []: pie(profit, labels=year) \end{lstlisting} \begin{lstlisting} - bar(year, profit) + In []: bar(year, profit) \end{lstlisting} \end{frame} @@ -388,11 +388,11 @@ \item Plot a \texttt{log-log} chart of $y=5x^3$ for x from 1 to 20 \end{itemize} \begin{lstlisting} - x = linspace(1,20,100) - y = 5*x**3 + In []: x = linspace(1,20,100) + In []: y = 5*x**3 - loglog(x, y) - plot(x, y) + In []: loglog(x, y) + In []: plot(x, y) \end{lstlisting} \begin{itemize} \item Look at \url{http://matplotlib.sourceforge.net/contents.html} diff --git a/basic_python/slides/func.tex b/basic_python/slides/func.tex index f0ed1a5..b66be06 100644 --- a/basic_python/slides/func.tex +++ b/basic_python/slides/func.tex @@ -20,11 +20,12 @@ \item Let's write a Python function, equivalent to this \end{itemize} \begin{lstlisting} - def f(x): - return x*x + In[]: def f(x): + ....: return x*x + ....: - f(1) - f(2) + In[]: f(1) + In[]: f(2) \end{lstlisting} \begin{itemize} \item \texttt{def} is a keyword @@ -38,10 +39,11 @@ \begin{frame}[fragile] \frametitle{Defining functions \ldots} \begin{lstlisting} - def greet(): - print "Hello World!" + In[]: def greet(): + ....: print "Hello World!" + ....: - greet() + In[]: greet() \end{lstlisting} \begin{itemize} \item \texttt{greet} is a function that takes no arguments @@ -49,10 +51,11 @@ \item But implicitly, Python returns \texttt{None} \end{itemize} \begin{lstlisting} - def avg(a, b): - return (a + b)/2 - - avg(12, 10) + In[]: def avg(a, b): + ....: return (a + b)/2 + ....: + + In[]: avg(12, 10) \end{lstlisting} \end{frame} @@ -63,14 +66,15 @@ \item We write a doc-string along with the function definition \end{itemize} \begin{lstlisting} - def avg(a, b): - """ avg takes two numbers as input - and returns their average""" + In[]: def avg(a, b): + """ avg takes two numbers as input + and returns their average""" - return (a + b)/2 + ....: return (a + b)/2 + ....: - avg? - greet? + In[]: avg? + In[]: greet? \end{lstlisting} \end{frame} @@ -81,19 +85,20 @@ \item Function needs to return two values \end{itemize} \begin{lstlisting} - def circle(r): - """returns area and perimeter of a - circle given, the radius r""" - - pi = 3.14 - area = pi * r * r - perimeter = 2 * pi * r - return area, perimeter - - circle(4) - a, p = circle(6) - print a - print p + In[]: def circle(r): + """returns area and perimeter of a + circle given, the radius r""" + + ....: pi = 3.14 + ....: area = pi * r * r + ....: perimeter = 2 * pi * r + ....: return area, perimeter + ....: + + In[]: circle(4) + In[]: a, p = circle(6) + In[]: print a + In[]: print p \end{lstlisting} \begin{itemize} \item Any number of values can be returned @@ -103,24 +108,26 @@ \begin{frame}[fragile] \frametitle{What? -- 1} \begin{lstlisting} - def what( n ): - if n < 0: n = -n - while n > 0: - if n % 2 == 1: - return False - n /= 10 - return True + In[]: def what( n ): + ....: if n < 0: n = -n + ....: while n > 0: + ....: if n % 2 == 1: + ....: return False + ....: n /= 10 + ....: return True + ....: \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{What? -- 2} \begin{lstlisting} - def what( n ): - i = 1 - while i * i < n: - i += 1 - return i * i == n, i + In[]: def what( n ): + ....: i = 1 + ....: while i * i < n: + ....: i += 1 + ....: return i * i == n, i + ....: \end{lstlisting} \end{frame} @@ -129,50 +136,53 @@ \begin{frame}[fragile] \frametitle{Default arguments} \begin{lstlisting} - round(2.484) - round(2.484, 2) + In[]: round(2.484) + In[]: round(2.484, 2) - s.split() # split on spaces - s.split(';') # split on ';' + In[]: s.split() # split on spaces + In[]: s.split(';') # split on ';' - range(10) # returns numbers from 0 to 9 - range(1, 10) # returns numbers from 1 to 9 - range(1, 10, 2) # returns odd numbers from 1 to 9 + In[]: range(10) # returns numbers from 0 to 9 + In[]: range(1, 10) # returns numbers from 1 to 9 + In[]: range(1, 10, 2) # returns odd numbers from 1 to 9 \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{Default arguments \ldots} \begin{lstlisting} - def welcome(greet, name="World"): - print greet, name + In[]: def welcome(greet, name="World"): + ....: print greet, name + ....: - welcome("Hi", "Guido") - welcome("Hello") + In[]: welcome("Hi", "Guido") + In[]: welcome("Hello") \end{lstlisting} \begin{itemize} \item Arguments with default values, should be placed at the end \item The following definition is \alert{WRONG} \end{itemize} \begin{lstlisting} - def welcome(name="World", greet): - print greet, name + In[]: def welcome(name="World", greet): + ....: print greet, name + ....: \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{Keyword Arguments} \begin{lstlisting} - def welcome(greet, name="World"): - print greet, name + In[]: def welcome(greet, name="World"): + ....: print greet, name + ....: - welcome("Hello", "James") + In[]: welcome("Hello", "James") - welcome("Hi", name="Guido") + In[]: welcome("Hi", name="Guido") - welcome(name="Guido", greet="Hey") + In[]: welcome(name="Guido", greet="Hey") - welcome(name="Guido", "Hey") + In[]: welcome(name="Guido", "Hey") \end{lstlisting} \end{frame} @@ -192,39 +202,58 @@ \begin{frame}[fragile] \frametitle{Arguments are local} \begin{lstlisting} - def change(q): - q = 10 - print q + In[]: def change(q): + ....: q = 10 + ....: print q + ....: - change(1) - print q + In[]: change(1) + In[]: print q \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{Variables inside function are local} \begin{lstlisting} - n = 5 - def change(): - n = 10 - print n - change() - print n + In[]: n = 5 + In[]: def change(): + ....: n = 10 + ....: print n + ....: + In[]: change() + In[]: print n \end{lstlisting} \begin{itemize} \item Use the \texttt{global} statement to assign to global variables \end{itemize} \begin{lstlisting} - def change(): - global n - n = 10 - print n - change() - print n + In[]: def change(): + ....: global n + ....: n = 10 + ....: print n + ....: + In[]: change() + In[]: print n \end{lstlisting} \end{frame} \begin{frame}[fragile] + \frametitle{global} + \begin{itemize} + \item Use the \texttt{global} statement to assign to global variables + \end{itemize} + \begin{lstlisting} + In[]: def change(): + ....: global n + ....: n = 10 + ....: print n + ....: + In[]: change() + In[]: print n + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] \frametitle{Mutable variables} \begin{itemize} \item Behavior is different when assigning to a list element/slice @@ -232,31 +261,34 @@ until the name is found \end{itemize} \begin{lstlisting} - name = ['Mr.', 'Steve', 'Gosling'] - def change_name(): - name[0] = 'Dr.' - change_name() - print name + In[]: name = ['Mr.', 'Steve', 'Gosling'] + In[]: def change_name(): + ....: name[0] = 'Dr.' + ....: + In[]: change_name() + In[]: print name \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{Passing Arguments \ldots} \begin{lstlisting} - n = 5 - def change(n): - n = 10 - print "n = %s inside change " %n - change(n) - print n + In[]: n = 5 + In[]: def change(n): + ....: n = 10 + ....: print "n = %s inside change " %n + ....: + In[]: change(n) + In[]: print n \end{lstlisting} \begin{lstlisting} - name = ['Mr.', 'Steve', 'Gosling'] - def change_name(n): - n[0] = 'Dr.' - print "n = %s inside change_name" %n - change_name(name) - print name + In[]: name = ['Mr.', 'Steve', 'Gosling'] + In[]: def change_name(n): + ....: n[0] = 'Dr.' + ....: print "n = %s inside change_name" %n + ....: + In[]: change_name(name) + In[]: print name \end{lstlisting} \end{frame} diff --git a/basic_python/slides/io_files_parsing.tex b/basic_python/slides/io_files_parsing.tex index 0fa030a..cb46cbe 100644 --- a/basic_python/slides/io_files_parsing.tex +++ b/basic_python/slides/io_files_parsing.tex @@ -3,9 +3,9 @@ \begin{frame}[fragile] \frametitle{Printing} \begin{lstlisting} - a = "This is a string" - a - print a + In[]: a = "This is a string" + In[]: a + In[]: print a \end{lstlisting} \begin{itemize} \item Both \texttt{a}, and \texttt{print a} are showing the value @@ -15,19 +15,19 @@ \item In a script, it has no effect. \end{itemize} \begin{lstlisting} - b = "A line \n New line" - b - print b + In[]: b = "A line \n New line" + In[]: b + In[]: print b \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{String formatting} \begin{lstlisting} - x = 1.5 - y = 2 - z = "zed" - print "x is %2.1f y is %d z is %s" %(x, y, z) + In[]: x = 1.5 + In[]: y = 2 + In[]: z = "zed" + In[]: print "x is %2.1f y is %d z is %s" %(x, y, z) \end{lstlisting} \end{frame} @@ -39,11 +39,11 @@ \item Save as \texttt{print\_example.py} \end{itemize} \begin{lstlisting} - print "Hello" - print "World" + In[]: print "Hello" + In[]: print "World" - print "Hello", - print "World" + In[]: print "Hello", + In[]: print "World" \end{lstlisting} \begin{itemize} \item Run the script using \texttt{\% run print\_example.py} @@ -55,30 +55,30 @@ \begin{frame}[fragile] \frametitle{\texttt{raw\_input}} \begin{lstlisting} - ip = raw_input() + In[]: ip = raw_input() \end{lstlisting} \begin{itemize} \item The cursor is blinking; waiting for input \item Type \texttt{an input} and hit <ENTER> \end{itemize} \begin{lstlisting} - print ip + In[]: print ip \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{\texttt{raw\_input} \ldots} \begin{lstlisting} - c = raw_input() - 5.6 - c - type(c) + In[]: c = raw_input() + In[]: 5.6 + In[]: c + In[]: type(c) \end{lstlisting} \begin{itemize} \item \alert{\texttt{raw\_input} always takes a string} \end{itemize} \begin{lstlisting} - name = raw_input("Please enter your name: ") + In[]: name = raw_input("Please enter your name: ") George \end{lstlisting} \begin{itemize} @@ -96,8 +96,8 @@ \end{lstlisting} {\tiny The file is in our present working directory} \begin{lstlisting} - f = open('pendulum.txt') - f + In[]: f = open('pendulum.txt') + In[]: f \end{lstlisting} \begin{itemize} \item \texttt{f} is a file object @@ -108,16 +108,16 @@ \begin{frame}[fragile] \frametitle{Reading the whole file} \begin{lstlisting} - pend = f.read() - print pend + In[]: pend = f.read() + In[]: print pend \end{lstlisting} \begin{itemize} \item We have read the whole file into the variable \texttt{pend} \end{itemize} \begin{lstlisting} - type(pend) - pend_list = pend.splitlines() - pend_list + In[]: type(pend) + In[]: pend_list = pend.splitlines() + In[]: pend_list \end{lstlisting} \begin{itemize} \item \texttt{pend} is a string variable @@ -126,16 +126,16 @@ \item Close the file, when done; Also, if you want to read again \end{itemize} \begin{lstlisting} - f.close() - f + In[]: f.close() + In[]: f \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{Reading line-by-line} \begin{lstlisting} - for line in open('pendulum.txt'): - print line + In[]: for line in open('pendulum.txt'): + ....: print line \end{lstlisting} \begin{itemize} \item The file object is an ``iterable'' @@ -143,9 +143,9 @@ \item Instead of printing, collect lines in a list \end{itemize} \begin{lstlisting} - line_list = [ ] - for line in open('pendulum.txt'): - line_list.append(line) + In[]: line_list = [ ] + In[]: for line in open('pendulum.txt'): + ....: line_list.append(line) \end{lstlisting} \end{frame} @@ -171,8 +171,8 @@ \begin{frame}[fragile] \frametitle{Tokenization} \begin{lstlisting} - line = "parse this string" - line.split() + In[]: line = "parse this string" + In[]: line.split() \end{lstlisting} \begin{itemize} \item Original string is split on white-space (if no argument) @@ -180,8 +180,8 @@ \item It can be given an argument to split on that argrument \end{itemize} \begin{lstlisting} - record = "A;015163;JOSEPH RAJ S;083;042;47;AA;72;244;;;" - record.split(';') + In[]: record = "A;015163;JOSEPH RAJ S;083;042;47;AA;72;244;;;" + In[]: record.split(';') \end{lstlisting} \end{frame} @@ -192,8 +192,8 @@ \item We can strip out the spaces at the ends \end{itemize} \begin{lstlisting} - word = " B " - word.strip() + In[]: word = " B " + In[]: word.strip() \end{lstlisting} \begin{itemize} \item \texttt{strip} is returning a new string @@ -207,10 +207,10 @@ \item We need numbers to perform math operations \end{itemize} \begin{lstlisting} - mark_str = "1.25" - mark = int(mark_str) - type(mark_str) - type(mark) + In[]: mark_str = "1.25" + In[]: mark = int(mark_str) + In[]: type(mark_str) + In[]: type(mark) \end{lstlisting} \begin{itemize} \item \texttt{strip} is returning a new string @@ -220,20 +220,20 @@ \begin{frame}[fragile] \frametitle{File parsing -- Solution} \begin{lstlisting} - math_B = [] # empty list to store marks - for line in open("sslc1.txt"): - fields = line.split(";") + In[]: math_B = [] # empty list to store marks + In[]: for line in open("sslc1.txt"): + ....: fields = line.split(";") - reg_code = fields[0] - reg_code_clean = reg_code.strip() + ....: reg_code = fields[0] + ....: reg_code_clean = reg_code.strip() - math_mark_str = fields[5] - math_mark = float(math_mark_str) + ....: math_mark_str = fields[5] + ....: math_mark = float(math_mark_str) - if reg_code == "B": - math_B.append(math_mark) + ....: if reg_code == "B": + ....: math_B.append(math_mark) - math_B_mean = sum(math_B) / len(math_B) - math_B_mean + In[]: math_B_mean = sum(math_B) / len(math_B) + In[]: math_B_mean \end{lstlisting} \end{frame} diff --git a/basic_python/slides/strings_loops_lists.tex b/basic_python/slides/strings_loops_lists.tex index 3d6d8e8..26d7b54 100644 --- a/basic_python/slides/strings_loops_lists.tex +++ b/basic_python/slides/strings_loops_lists.tex @@ -8,11 +8,11 @@ \item Any length --- single character, null string, \ldots \end{itemize} \begin{lstlisting} - 'This is a string' - "This is a string too' - '''This is a string as well''' - """This is also a string""" - '' # empty string + In[]: 'This is a string' + In[]: "This is a string too' + In[]: '''This is a string as well''' + In[]: """This is also a string""" + In[]: '' # empty string \end{lstlisting} \end{frame} @@ -22,8 +22,8 @@ \item Reduce the need for escaping \end{itemize} \begin{lstlisting} - "Python's strings are powerful!" - 'He said, "I love Python!"' + In[]: "Python's strings are powerful!" + In[]: 'He said, "I love Python!"' \end{lstlisting} \begin{itemize} \item Triple quoted strings can be multi-line @@ -34,29 +34,29 @@ \begin{frame}[fragile] \frametitle{Assignment \& Operations} \begin{lstlisting} - a = 'Hello' - b = 'World' - c = a + ', ' + b + '!' + In[]: a = 'Hello' + In[]: b = 'World' + In[]: c = a + ', ' + b + '!' \end{lstlisting} \begin{itemize} \item Strings can be multiplied with numbers \end{itemize} \begin{lstlisting} - a = 'Hello' - a * 5 + In[]: a = 'Hello' + In[]: a * 5 \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{Accessing Elements} \begin{lstlisting} - print a[0], a[4], a[-1], a[-4] + In[]: print a[0], a[4], a[-1], a[-4] \end{lstlisting} \begin{itemize} \item Can we change the elements? \end{itemize} \begin{lstlisting} - a[0] = 'H' + In[]: a[0] = 'H' \end{lstlisting} \begin{itemize} \item Strings are immutable! @@ -84,13 +84,13 @@ \begin{frame}[fragile] \frametitle{Slicing} \begin{lstlisting} - q = "Hello World" - q[0:3] - q[:3] - q[3:] - q[:] - q[-1:1] - q[1:-1] + In[]: q = "Hello World" + In[]: q[0:3] + In[]: q[:3] + In[]: q[3:] + In[]: q[:] + In[]: q[-1:1] + In[]: q[1:-1] \end{lstlisting} \begin{itemize} \item One or both of the limits, is optional @@ -100,22 +100,22 @@ \begin{frame}[fragile] \frametitle{Striding} \begin{lstlisting} - q[0:5:1] - q[0:5:2] - q[0:5:3] - q[0::2] - q[2::2] - q[::2] - q[5:0:-1] - q[::-1] + In[]: q[0:5:1] + In[]: q[0:5:2] + In[]: q[0:5:3] + In[]: q[0::2] + In[]: q[2::2] + In[]: q[::2] + In[]: q[5:0:-1] + In[]: q[::-1] \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{String Methods} \begin{lstlisting} - s.lower() - s.upper() + In[]: s.lower() + In[]: s.upper() s.<TAB> \end{lstlisting} \begin{itemize} @@ -127,11 +127,11 @@ \begin{frame}[fragile] \frametitle{Solution - Day of the Week?} \begin{lstlisting} - s.lower()[:3] in week + In[]: s.lower()[:3] in week \end{lstlisting} OR \begin{lstlisting} - s[:3].lower() in week + In[]: s[:3].lower() in week \end{lstlisting} \end{frame} @@ -143,13 +143,13 @@ \item Possibly, each string separated by a common token \end{itemize} \begin{lstlisting} - email_list = ["info@fossee.in", + In[]: email_list = ["info@fossee.in", "enquiries@fossee.in", "help@fossee.in"] \end{lstlisting} \begin{lstlisting} - '; '.join(email_list) - ', '.join(email_list) + In[]: '; '.join(email_list) + In[]: ', '.join(email_list) \end{lstlisting} \end{frame} @@ -158,11 +158,11 @@ \begin{frame}[fragile] \frametitle{\texttt{if-else} block} \begin{lstlisting} - a = 5 - if a % 2 == 0: - print "Even" - else: - print "Odd" + In[]: a = 5 + In[]: if a % 2 == 0: + ....: print "Even" + ....: else: + ....: print "Odd" \end{lstlisting} \begin{itemize} \item A code block -- \texttt{:} and indentation @@ -174,12 +174,12 @@ \begin{frame}[fragile] \frametitle{\texttt{if-elif-else}} \begin{lstlisting} - if a > 0: - print "positive" - elif a < 0: - print "negative" - else: - print "zero" + In[]: if a > 0: + ....: print "positive" + ....: elif a < 0: + ....: print "negative" + ....: else: + ....: print "zero" \end{lstlisting} \begin{itemize} \item Only one block gets executed, depending on \texttt{a} @@ -189,12 +189,12 @@ \begin{frame}[fragile] \frametitle{\texttt{else} is optional} \begin{lstlisting} - if user == 'admin': - admin_Operations() - elif user == 'moderator': - moderator_operations() - elif user == 'client': - customer_operations() + In[]: if user == 'admin': + ....: admin_Operations() + ....: elif user == 'moderator': + ....: moderator_operations() + ....: elif user == 'client': + ....: customer_operations() \end{lstlisting} \begin{itemize} \item Note that there is no \texttt{else} block @@ -211,14 +211,14 @@ \item \texttt{if-else} construct or the ternary operator \end{itemize} \begin{lstlisting} - if score_str != 'AA': - score = int(score_str) - else: - score = 0 + In[]: if score_str != 'AA': + ....: score = int(score_str) + ....: else: + ....: score = 0 \end{lstlisting} \begin{lstlisting} - ss = score_str - score = int(ss) if ss != 'AA' else 0 + In[]: ss = score_str + In[]: score = int(ss) if ss != 'AA' else 0 \end{lstlisting} \end{frame} @@ -242,11 +242,11 @@ \texttt{while} \end{itemize} \begin{lstlisting} - i = 1 + In[]: i = 1 - while i<10: - print i*i - i += 2 + In[]: while i<10: + ....: print i*i + ....: i += 2 \end{lstlisting} \begin{itemize} \item The loops runs as long as the condition is \texttt{True} @@ -260,18 +260,18 @@ \texttt{for} \end{itemize} \begin{lstlisting} - for n in [1, 2, 3]: - print n + In[]: for n in [1, 2, 3]: + ....: print n \end{lstlisting} \begin{itemize} \item \texttt{for} iterates over each element of a sequence \end{itemize} \begin{lstlisting} - for n in [1, 3, 5, 7, 9]: - print n*n + In[]: for n in [1, 3, 5, 7, 9]: + ....: print n*n - for n in range(1, 10, 2): - print n*n + In[]: for n in range(1, 10, 2): + ....: print n*n \end{lstlisting} \begin{itemize} \item \alert{range([start,] stop[, step])} @@ -288,13 +288,13 @@ \texttt{break} \end{itemize} \begin{lstlisting} - i = 1 + In[]: i = 1 - while True: - print i*i - i += 2 - if i>10: - break + In[]: while True: + ....: print i*i + ....: i += 2 + ....: if i>10: + ....: break \end{lstlisting} \end{frame} @@ -306,10 +306,10 @@ \item Squares of all odd numbers below 10, not multiples of 3 \end{itemize} \begin{lstlisting} - for n in range(1, 10, 2): - if n%3 == 0: - continue - print n*n + In[]: for n in range(1, 10, 2): + ....: if n%3 == 0: + ....: continue + ....: print n*n \end{lstlisting} \end{frame} @@ -319,10 +319,10 @@ \begin{frame}[fragile] \frametitle{Creating Lists} \begin{lstlisting} - empty = [] + In[]: empty = [] - p = ['spam', 'eggs', 100, 1.234] - q = [[4, 2, 3, 4], 'and', 1, 2, 3, 4] + In[]: p = ['spam', 'eggs', 100, 1.234] + In[]: q = [[4, 2, 3, 4], 'and', 1, 2, 3, 4] \end{lstlisting} \begin{itemize} \item Lists can be empty, with no elements in them @@ -333,10 +333,10 @@ \begin{frame}[fragile] \frametitle{Accessing Elements} \begin{lstlisting} - print p[0], p[1], p[3] + In[]: print p[0], p[1], p[3] - print p[-1], p[-2], p[-4] - print p[10] + In[]: print p[-1], p[-2], p[-4] + In[]: print p[10] \end{lstlisting} \begin{itemize} \item Indexing starts from 0 @@ -348,11 +348,11 @@ \begin{frame}[fragile] \frametitle{Accessing Elements \& length} \begin{lstlisting} - print p[0], p[1], p[3] + In[]: print p[0], p[1], p[3] - print p[-1], p[-2], p[-4] - print len(p) - print p[10] + In[]: print p[-1], p[-2], p[-4] + In[]: print len(p) + In[]: print p[10] \end{lstlisting} \begin{itemize} \item Indexing starts from 0 @@ -368,18 +368,18 @@ \item The append method adds elements to the end of the list \end{itemize} \begin{lstlisting} - p.append('onemore') - p - p.append([1, 6]) - p + In[]: p.append('onemore') + In[]: p + In[]: p.append([1, 6]) + In[]: p \end{lstlisting} \begin{itemize} \item Elements can be removed based on their index OR \item based on the value of the element \end{itemize} \begin{lstlisting} - del p[1] - p.remove(100) + In[]: del p[1] + In[]: p.remove(100) \end{lstlisting} \begin{itemize} \item \alert{When removing by value, first element is removed} @@ -390,68 +390,68 @@ \begin{frame}[fragile] \frametitle{Concatenating lists} \begin{lstlisting} - a = [1, 2, 3, 4] - b = [4, 5, 6, 7] - a + b - print a+b, a, b + In[]: a = [1, 2, 3, 4] + In[]: b = [4, 5, 6, 7] + In[]: a + b + In[]: print a+b, a, b \end{lstlisting} \begin{itemize} \item A new list is returned; None of the original lists change \end{itemize} \begin{lstlisting} - c = a + b - c + In[]: c = a + b + In[]: c \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{Slicing \& Striding} \begin{lstlisting} - primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] - primes[4:8] - primes[:4] + In[]: primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] + In[]: primes[4:8] + In[]: primes[:4] - num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] - num[1:10:2] - num[:10] - num[10:] - num[::2] - num[::-1] + In[]: num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] + In[]: num[1:10:2] + In[]: num[:10] + In[]: num[10:] + In[]: num[::2] + In[]: num[::-1] \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{Sorting} \begin{lstlisting} - a = [5, 1, 6, 7, 7, 10] - a.sort() - a + In[]: a = [5, 1, 6, 7, 7, 10] + In[]: a.sort() + In[]: a \end{lstlisting} \begin{itemize} \item \texttt{sort} method sorts the list in-place \item Use \texttt{sorted} if you require a new list \end{itemize} \begin{lstlisting} - a = [5, 1, 6, 7, 7, 10] - sorted(a) - a + In[]: a = [5, 1, 6, 7, 7, 10] + In[]: sorted(a) + In[]: a \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{Reversing} \begin{lstlisting} - a = [5, 1, 6, 7, 7, 10] - a.reverse() - a + In[]: a = [5, 1, 6, 7, 7, 10] + In[]: a.reverse() + In[]: a \end{lstlisting} \begin{itemize} \item \texttt{reverse} method reverses the list in-place \item Use \texttt{[::-1]} if you require a new list \end{itemize} \begin{lstlisting} - a = [5, 1, 6, 7, 7, 10] - a[::-1] - a + In[]: a = [5, 1, 6, 7, 7, 10] + In[]: a[::-1] + In[]: a \end{lstlisting} \end{frame} diff --git a/basic_python/slides/tuples_dicts_sets.tex b/basic_python/slides/tuples_dicts_sets.tex index 29dadba..b09fd99 100644 --- a/basic_python/slides/tuples_dicts_sets.tex +++ b/basic_python/slides/tuples_dicts_sets.tex @@ -3,24 +3,24 @@ \begin{frame}[fragile] \frametitle{Tuples -- Initialization} \begin{lstlisting} - t = (1, 2.5, "hello", -4, "world", 1.24, 5) - t + In[]: t = (1, 2.5, "hello", -4, "world", 1.24, 5) + In[]: t \end{lstlisting} \begin{itemize} \item It is not always necessary to use parenthesis \end{itemize} \begin{lstlisting} - a = 1, 2, 3 - b = 1, + In[]: a = 1, 2, 3 + In[]: b = 1, \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{Indexing} \begin{lstlisting} - t[3] - t[1:5:2] - t[2] = "Hello" + In[]: t[3] + In[]: t[1:5:2] + In[]: t[2] = "Hello" \end{lstlisting} \begin{itemize} \item \alert{Tuples are immutable!} @@ -30,41 +30,41 @@ \begin{frame}[fragile] \frametitle{Swapping values} \begin{lstlisting} - a = 5 - b = 7 + In[]: a = 5 + In[]: b = 7 - temp = a - a = b - b = temp + In[]: temp = a + In[]: a = b + In[]: b = temp \end{lstlisting} \begin{itemize} \item Here's the Pythonic way of doing it \end{itemize} \begin{lstlisting} - a, b = b, a + In[]: a, b = b, a \end{lstlisting} \begin{itemize} \item The variables can be of different data-types \end{itemize} \begin{lstlisting} - a = 2.5 - b = "hello" - a, b = b, a + In[]: a = 2.5 + In[]: b = "hello" + In[]: a, b = b, a \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{Tuple packing \& unpacking} \begin{lstlisting} - 5, + In[]: 5, - 5, "hello", 2.5 + In[]: 5, "hello", 2.5 \end{lstlisting} \begin{itemize} \item Tuple packing and unpacking, when swapping \end{itemize} \begin{lstlisting} - a, b = b, a + In[]: a, b = b, a \end{lstlisting} \end{frame} @@ -73,14 +73,14 @@ \begin{frame}[fragile] \frametitle{Creating Dictionaries} \begin{lstlisting} - mt_dict = {} + In[]: mt_dict = {} - extensions = {'jpg' : 'JPEG Image', + In[]: extensions = {'jpg' : 'JPEG Image', 'py' : 'Python script', 'html' : 'Html document', 'pdf' : 'Portable Document Format'} - extensions + In[]: extensions \end{lstlisting} \begin{itemize} \item Key-Value pairs @@ -91,13 +91,13 @@ \begin{frame}[fragile] \frametitle{Accessing Elements} \begin{lstlisting} - print extensions['jpg'] + In[]: print extensions['jpg'] \end{lstlisting} \begin{itemize} \item Values can be accessed using keys \end{itemize} \begin{lstlisting} - print extensions['zip'] + In[]: print extensions['zip'] \end{lstlisting} \begin{itemize} \item Values of non-existent keys cannot, obviously, be accessed @@ -110,30 +110,30 @@ \item Adding a new key-value pair \end{itemize} \begin{lstlisting} - extensions['cpp'] = 'C++ code' - extensions + In[]: extensions['cpp'] = 'C++ code' + In[]: extensions \end{lstlisting} \begin{itemize} \item Deleting a key-value pair \end{itemize} \begin{lstlisting} - del extension['pdf'] - extensions + In[]: del extension['pdf'] + In[]: extensions \end{lstlisting} \begin{itemize} \item Assigning to existing key, modifies the value \end{itemize} \begin{lstlisting} - extensions['cpp'] = 'C++ source code' - extensions + In[]: extensions['cpp'] = 'C++ source code' + In[]: extensions \end{lstlisting} \end{frame} \begin{frame}[fragile] \frametitle{Containership} \begin{lstlisting} - 'py' in extensions - 'odt' in extensions + In[]: 'py' in extensions + In[]: 'odt' in extensions \end{lstlisting} \begin{itemize} \item Allow checking for container-ship of keys; NOT values @@ -144,16 +144,17 @@ \begin{frame}[fragile] \frametitle{Lists of Keys and Values} \begin{lstlisting} - extensions.keys() - extensions.values() + In[]: extensions.keys() + In[]: extensions.values() \end{lstlisting} \begin{itemize} \item Note that the order of the keys and values match \item That can be relied upon and used \end{itemize} \begin{lstlisting} - for each in extensions.keys(): - print each, "-->", extensions[each] + In[]: for each in extensions.keys(): + ....: print each, "-->", extensions[each] + ....: \end{lstlisting} \end{frame} @@ -162,9 +163,9 @@ \begin{frame}[fragile] \frametitle{Creating Sets} \begin{lstlisting} - a_list = [1, 2, 1, 4, 5, 6, 2] - a = set(a_list) - a + In[]: a_list = [1, 2, 1, 4, 5, 6, 2] + In[]: a = set(a_list) + In[]: a \end{lstlisting} \begin{itemize} \item Conceptually identical to the sets in mathematics @@ -176,8 +177,8 @@ \begin{frame}[fragile] \frametitle{Operations on Sets} \begin{lstlisting} - f10 = set([1, 2, 3, 5, 8]) - p10 = set([2, 3, 5, 7]) + In[]: f10 = set([1, 2, 3, 5, 8]) + In[]: p10 = set([2, 3, 5, 7]) \end{lstlisting} \begin{itemize} \item Mathematical operations performed on sets, can be performed @@ -185,19 +186,19 @@ \begin{itemize} \item Union \begin{lstlisting} - f10 | p10 + In[]: f10 | p10 \end{lstlisting} \item Intersection \begin{lstlisting} - f10 & p10 + In[]: f10 & p10 \end{lstlisting} \item Difference \begin{lstlisting} - f10 - p10 + In[]: f10 - p10 \end{lstlisting} \item Symmetric Difference \begin{lstlisting} - f10 ^ p10 + In[]: f10 ^ p10 \end{lstlisting} \end{itemize} \end{frame} @@ -207,12 +208,12 @@ \begin{itemize} \item Proper Subset \begin{lstlisting} - b = set([1, 2]) - b < f10 + In[]: b = set([1, 2]) + In[]: b < f10 \end{lstlisting} \item Subsets \begin{lstlisting} - f10 <= f10 + In[]: f10 <= f10 \end{lstlisting} \end{itemize} \end{frame} @@ -222,17 +223,18 @@ \begin{itemize} \item Containership \begin{lstlisting} - 1 in f10 - 4 in f10 + In[]: 1 in f10 + In[]: 4 in f10 \end{lstlisting} \item Iterating over elements \begin{lstlisting} - for i in f10: - print i, + In[]: for i in f10: + ....: print i, + ....: \end{lstlisting} \item Subsets \begin{lstlisting} - f10 <= f10 + In[]: f10 <= f10 \end{lstlisting} \end{itemize} \end{frame} @@ -244,13 +246,13 @@ all the duplicates \end{block} \begin{lstlisting} - marks = [20, 23, 22, 23, 20, 21, 23] - marks_set = set(marks) - for mark in marks_set: - marks.remove(mark) + In[]: marks = [20, 23, 22, 23, 20, 21, 23] + In[]: marks_set = set(marks) + In[]: for mark in marks_set: + ....: marks.remove(mark) # left with only duplicates - duplicates = set(marks) + In[]: duplicates = set(marks) \end{lstlisting} \end{frame} |