[PDF] CS229 Section: Python Tutorial





Previous PDF Next PDF



Python Tutorial

2 Sept 2018 3 is a prime number. 4 equals 2 * 2. 5 is a prime number. 6 equals 2 * 3. 7 is a prime number. 8 equals 2 * 4. 9 equals 3 * 3. (Yes this is the ...



Python Tutorial

27 May 2013 9 equals 3 * 3. (Yes this is the correct code. Look closely: the ... This tutorial is part of Python's documentation set. Some other ...



Python Tutorial

18 Jun 2012 Python Tutorial Release 3.2.3. Ng Pheng Siong



Python Full Tutorial

21 Sept 2023 So start. Page 3. Python Tutorial ii learning Python using this simple and effective tutorial from anywhere and anytime absolutely at your pace ...



An ns-3 tutorial

ns-3 uses the waf build system simulation programs are C++ executables or python scripts. API documentation using doxygen. Mathieu Lacage (INRIA). An ns-3 



ns-3-tutorial.pdf

ns-3 has optional Python bindings for authoring scenario configuration programs in Python (and using a Python-based workflow); this quick start does not 



ns-3 Tutorial - Release ns-3.29 ns-3 project

8 Jan 2019 As mentioned above scripting in ns-3 is done in C++ or Python. Most of the ns-3 API is available in Python



ns-3 Tutorial

27 Sept 2023 ns-3 has optional Python bindings for authoring scenario configuration programs in Python (and using a Python-based workflow); this quick ...



Python Tutorial

24 Jan 2022 Thanks to the MIT Python Course and the Python 3 Tutorial. 1 / 57. Page 2. Why Python? Figure: Top 10 Programming Languages by IEEE Spectrum ...



Solving PDEs in Python – The FEniCS Tutorial Volume I

to enable the print function from Python 3 in Python 2. All use of print in the programs in this tutorial consists of function calls like print('a:'



Python 3 - Tutorialspoint

17?/02?/2016 This tutorial can also be used to learn Python programming language from scratch. Prerequisites. You should have a basic understanding of ...



Python Tutorial

02?/09?/2018 1 On Unix the Python 3.x interpreter is by default not installed with the executable named python



cours-python.pdf

22?/03?/2018 1. https://docs.python.org/fr/3/tutorial/floatingpoint.html. Cours de Python / Université Paris Cité / UFR Sciences du Vivant.



Non-Programmers Tutorial for Python 3/Print version - Wikibooks

14?/01?/2016 Before computers had screens the output of computer programs would be printed on paper.) Note that this is a Python 3 tutorial



Python Tutorial

27?/05?/2013 This tutorial introduces the reader informally to the basic ... 1 On Unix the Python 3.x interpreter is by default not installed with the ...



ns-3 Tutorial

08?/01?/2019 In this tutorial we will build several example simulations



The Python GTK+ 3 Tutorial - Release 3.4 Sebastian Pölsterl

05?/03?/2022 The Python GTK+ 3 Tutorial Release 3.4. $ jhbuild build gtk+-3. To start a shell with the same environment as used by JHBuild



CS229 Section: Python Tutorial

NumPy compares dimensions of operands then infers missing/mismatched dimensions so the operation is still valid. Be careful with dimensions! array([[ 1



Apprendre à programmer avec Python 3 - INFOREF

modifications avant l'apparition de Python 3. Cette nouvelle version du langage a cependant apporté quelques changements de fond qui lui.



Python Tutorial

School of Computing. University of North Florida. Monday 1/24/2022. Thanks to the MIT Python Course and the Python 3 Tutorial.



Videos

A major overhaul Python 3 was released in late 2008 to address and amend intrinsic design ?aws of previous versions of the language The focus of Python 3 development was to clean up the codebase and remove redundancy making it clear that there was only one way to perform a given task Major modi?cations to Python 3 0 included changing



Python Tutorial

Python Tutorial Release 3 3 2 Python is an easy to learn powerful programming language It has ef?cient high-level data structures and a simple but effective approach to object-oriented programming Python’s elegant syntax and dynamic typing together



Python Basics: A Practical Introduction to Python 3

Hello and welcome to Python Basics: A Practical Introduction to Python3 Ihopeyou’rereadytolearnwhysomanyprofessionaland hobbyist developers are drawn to Python and how you can begin usingitonyourownprojectssmallandlargerightaway Thisbookistargetedatbeginnerswhoeitherknowalittleprogram-mingbutnotthePythonlanguageandecosystemorarestartingfresh



Installing IPython using pip — CSC 161 01 documentation

Python as his main programming language primarily as a means for creative ends because it is easy to read and fun to learn J-P Stacey has been a senior developer at Torchbox Ltd since 2005 building and maintaining (among other things) Python Django and Drupal applications



Searches related to python 3 tutorial filetype:pdf

1 CS131 Python 3 Tutorial Adapted by Ranjay Krishna from the CS228 Python 2 tutorial 1 1 Introduction Python is a great general-purpose programming language on its own but with the help of a few popularlibraries(numpyscipymatplotlib)itbecomesapowerfulenvironmentforscienti?ccom-puting

How to install Python 3 on Windows {Quickstart}?

    Quickstart¶. Use the Python 3 command pip3 to install IPython in a permanent, globally accessible location on your computer. Open a terminal prompt (such as OS X’s Terminal, or Windows’ Command Prompt) and type the command:

How do I install Python 3?

    Python 3 Installation on Windows. Step 1: Select Version of Python to Install; Step 2: Download Python Executable Installer; Step 3: Run Executable Installer; Step 4: Verify Python Was Installed On Windows ; Step 5: Verify Pip Was Installed; Step 6: Add Python Path to Environment Variables (Optional) Step 7: Install virtualnv (Optional)

Should I start with Python 3?

    We recommend sticking with Python 3.7 unless you have a specific reason for choosing something different. Once you've installed the Python extension, select a Python 3 interpreter by opening the Command Palette (Ctrl+Shift+P), start typing the command Python: Select Interpreter to search, then select the command.

Why to learn Python 3,?

    Why Should I Learn Python 3 ? Because of its adaptability, flexibility, and object-oriented characteristics, Python is one of the most popular programming languages among developers, data scientists, software engineers, and even hackers. Python’s rich libraries, frameworks, massive collections of modules, and file extensions are responsible ...
CS229 Section: Python TutorialMaya SrikanthContent adapted from past CS229 iterations

PythonPython 2.0 released in 2000(Python 2.7 "end-of-life" in 2020)Python 3.0 released in 2008(Python 3.6+ for CS 229)-High-level object-oriented,interpreted languagehttps://www.researchgate.net/figure/Genealogy-of-Programming-Languages-doi101371-journalpone0088941g001_fig1_260447599

Text editor/IDE options.. (don't settle with notepad)•PyCharm (IDE)•Visual Studio Code (IDE)•Sublime Text (IDE)•Atom•Notepad ++/gedit•Vim (for Linux)

PyCharm IDEPyCharm•Good debugger•Project managementFYI, professional version free for students: https://www.jetbrains.com/student/

Visual Studio IDEVisual Studio Code•Light weight•Wide variety of plugins to enable support for all languages

Basic Python: Strings, Lists, Dictionaries

String manipulationFormattingConcatenationFormattingprint('IloveCS229.(upper)'.upper())print('IloveCS229.(rjust20)'.rjust(20))print('weloveCS229.(capitalize)'.capitalize())print('IloveCS229.(strip)'.strip())print('Ilike'+str(cs_class_code)+'alot!')print(f'{print}(printafunction)')print(f'{type(229)}(printatype)')print('Oldschoolformatting:{.2F}'.format(1.358))

ListList creationInsertion/extensionList comprehensionSortinglong_list=[iforiinrange(9)]long_long_list=[(i,j)foriinrange(3)forjinrange(5)]long_list_list=[[iforiinrange(3)]for_inrange(5)]list_1=['one','two','three']list_1.append(4)list_1.insert(0,'ZERO')list_2=[1,2,3]list_1.extend(list_2)sorted(random_list)random_list_2=[(3,'z'),(12,'r'),(6,'e'),(8,'c'),(2,'g')]sorted(random_list_2,key=lambdax:x[1])

Dictionary and Setmy_set={i**2foriinrange(10)}my_dict={(5-i):i**2foriinrange(10)}{0, 1, 64, 4, 36, 9, 16, 49, 81, 25}{5: 0, 4: 1, 3: 4, 2: 9, 1: 16, 0: 25, -1: 36, -2: 49, -3: 64, -4: 81} dict_keys([5, 4, 3, 2, 1, 0, -1, -2, -3, -4])Set (unordered, unique)Dictionary (mapping)Dictionary updateIterate through itemssecond_dict={'a':10,'b':11}my_dict.update(second_dict)fork,itinmy_dict.items():print(k,it)

NumPy

What is NumPy and why?•Package for scientific computing in Python •Vector and matrix manipulation•Broadcasting and vectorization (matrixoperations)saves time & cleans up code

Convenient math functions, read before use!Python CommandDescriptionnp.linalg.invInverse of matrix (numpy as equivalent)np.linalg.eigGet eigen values & eigen vectors of arrnp.matmulMatrix multiplynp.zerosCreate a matrix filled with zeros (Read on np.ones)np.arangeStart, stop, step size (Read on np.linspace)np.identityCreate an identity matrixnp.vstackVertically stack 2 arrays (Read on np.hstack)

Debugging tools...Python CommandDescriptionarray.shapeGet shape of numpy arrayarray.dtypeCheck data type of array (for precision, for weird behavior)type(stuff)Get type of a variableimport pdb; pdb.set_trace()Set a breakpoint (https://docs.python.org/3/library/pdb.html)print(f'Myname is {name}')Easy way to construct a message

Basic NumPy UsageInitialization from Python listsLists with different types (NumPy auto-casts to higher precision, but it should be reasonably consistent)NumPy supports many types of algebra on an entire arrayarray_1d=np.array([1,2,3,4])array_1by4=np.array([[1,2,3,4]])large_array=np.array([iforiinrange(400)])large_array=large_array.reshape((20,20))array_1+5array_1*5np.sqrt(array_1)np.power(array_1,2)np.exp(array_1)np.log(array_1)from_list=np.array([1,2,3])from_list_2d=np.array([[1,2,3.0],[4,5,6]])from_list_bad_type=np.array([1,2,3,'a'])print(f'Datatypeofintegeris{from_list.dtype}')print(f'Datatypeoffloatis{from_list_2d.dtype}')

Dot product and matrix multiplicationA few ways to write dot productMatrix multiplication like Ax2D matrix multiplicationElement-wise multiplicationarray_1@array_2array_1.dot(array_2)np.dot(array_1,array_2)weight_matrix=np.array([1,2,3,4]).reshape(2,2)sample=np.array([[50,60]]).Tnp.matmul(weight_matrix,sample)mat1=np.array([[1,2],[3,4]])mat2=np.array([[5,6],[7,8]])np.matmul(mat1,mat2)a=np.array([iforiinrange(10)]).reshape(2,5)a*anp.multiply(a,a)np.multiply(a,10)

Broadcastingop1=np.array([iforiinrange(9)]).reshape(3,3)op2=np.array([[1,2,3]])op3=np.array([1,2,3])#NoticethattheresultshereareDIFFERENT!print(op1+op2)print(op1+op2.T)#NoticethattheresultshereareTHESAME!print(op1+op3)print(op1+op3.T)NumPy compares dimensions of operands, then infersmissing/mismatched dimensions so the operation is still valid. Be careful with dimensions!array([[ 1, 3, 5], [ 4, 6, 8], [ 7, 9, 11]])array([[ 1, 2, 3], [ 5, 6, 7], [ 9, 10, 11]])array([[ 1, 3, 5], [ 4, 6, 8], [ 7, 9, 11]])array([[ 1, 3, 5], [ 4, 6, 8], [ 7, 9, 11]])

Broadcasting for pairwise distancesamples=np.random.random((15,5))#Withoutbroadcastingexpanded1=np.expand_dims(samples,axis=1)tile1=np.tile(expanded1,(1,samples.shape[0],1))expanded2=np.expand_dims(samples,axis=0)tile2=np.tile(expanded2,(samples.shape[0],1,1))diff=tile2-tile1distances=np.linalg.norm(diff,axis=-1)#Withbroadcastingdiff=samples[:,np.newaxis,:]-samples[np.newaxis,:,:]distances=np.linalg.norm(diff,axis=-1)#With scipy(another math toolbox)importscipydistances=scipy.spatial.distance.cdist(samples,samples)Both achieve the effect of

Why should I vectorize my code? (dot product)Shorter code, faster executiona=np.random.random(500000)b=np.random.random(500000)print(np.array(a).dot(np.array(b)))dot=0.0foriinrange(len(a)):dot+=a[i]*b[i]print(dot)With loopNumpydot productWall time: 345msWall time: 2.9ms

An example with pairwise distanceSpeed up depends on setup and nature of computationWith loopNumpywith broadcastingWall time: 162ms(even worse without NumPy norm)Wall time: 3.5mssamples=np.random.random((100,5))total_dist=[]fors1insamples:fors2insamples:d=np.linalg.norm(s1-s2)total_dist.append(d)avg_dist=np.mean(total_dist)diff=samples[:,np.newaxis,:]-samples[np.newaxis,:,:]distances=np.linalg.norm(diff,axis=-1)avg_dist=np.mean(distances)

Tools for Plotting

Other Python packages/toolsJupyterNotebook•Interactive, re-execution, result storageMatplotlib / Seaborn•Visualization (line, scatter, bar, images and even interactive 3D)Pandas (https://pandas.pydata.org/)•DataFrame(database/Excel-like)•Easy filtering, aggregation (also plotting, but less features than dedicated datavispackages)

importmatplotlibimportmatplotlib.pyplotaspltimportnumpyasnp#Dataforplottingt=np.arange(0.0,2.0,0.01)s=1+np.sin(2*np.pi*t)fig,ax=plt.subplots()ax.plot(t,s)ax.set(xlabel='time(s)',ylabel='voltage(mV)',title='Aboutassimpleasitgets,folks')ax.grid()fig.savefig("test.png")plt.show()Example plotshttps://matplotlib.org/3.1.1/gallery/index.htmlImportCreate dataPlottingFormat plotSave/show

importnumpyasnpimportmatplotlib.pyplotaspltx=np.linspace(0,10,500)y=np.sin(x)fig,ax=plt.subplots()line1,=ax.plot(x,y,label='Usingset_dashes()')#2ptline,2ptbreak,10ptline,2ptbreakline1.set_dashes([2,2,10,2])line2,=ax.plot(x,y-0.2,dashes=[6,2],label='Usingthedashesparameter')ax.legend()plt.show()Plot with dash lines and legend

Using subplotx=np.arange(0,3*np.pi,0.1)y_sin=np.sin(x)y_cos=np.cos(x)#Setupgridwithheight2andcol1.#Plotthe1stsubplotplt.subplot(2,1,1)plt.grid()plt.plot(x,y_sin)plt.title('SineWave')#Nowplotonthe2ndsubplotplt.subplot(2,1,2)plt.plot(x,y_cos)plt.title('CosineWave')plt.grid()plt.tight_layout()

Plot area under curve

Confusion matrixhttps://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.htmlfig,ax=plt.subplots()im=ax.imshow(cm,interpolation='nearest',cmap=cmap)ax.figure.colorbar(im,ax=ax)#Wewanttoshowallticks...ax.set(xticks=np.arange(cm.shape[1]),yticks=np.arange(cm.shape[0]),xticklabels=classes,yticklabels=classes,ylabel='Truelabel',xlabel='Predictedlabel',title=title)#Rotatetheticklabelsandsettheiralignment.plt.setp(ax.get_xticklabels(),rotation=45,ha='right',rotation_mode='anchor')#Loopoverdatadimensionsandcreatetextannotations.fmt='.2f'ifnormalizeelse'd'thresh=cm.max()/2.foriinrange(cm.shape[0]):forjinrange(cm.shape[1]):ax.text(j,i,format(cm[i,j],fmt),ha='center',va='center',color="white"ifcm[i,j]>threshelse"black")fig.tight_layout()

DEMO...

Good luck on HW and projects!Questions?

Questions?Supplementary Slides

Where does my program start?It just worksProperlyA function

What is a class?Initialize the class to get an instanceusing some parametersDoes something with the instanceInstance variable

To use a classInstantiate a class,get an instanceCall an instance method

String manipulationFormattingstripped = ' I love CS229! '.strip()upper_case= 'ilove cs 229! '.upper()capitalized = 'ilove cs 229! '.capitalize()Concatenationjoined= 'string 1' + ' ' + 'string 2'Formattingformatted = 'Formatted number {.2F}'.format(1.2345)

Basic data structuresListexample_list= [1, 2, '3', 'four']Set (unordered, unique)example_set= set([1, 2, '3', 'four'])Dictionary (mapping)example_dictionary={'1': 'one','2': 'two','3': 'three'}

More on List2D listlist_of_list= [[1,2,3], [4,5,6], [7,8,9]]List comprehensioninitialize_a_list=[iforiinrange(9)]initialize_a_list=[i** 2foriinrange(9)]initialize_2d_list=[[i+ jforiinrange(5)] for j in range(9)]Insert/Popmy_list.insert(0, 'stuff)print(my_list.pop(0))

More on ListSort a listrandom_list = [3,12,5,6]sorted_list = sorted(random_list)random_list = [(3, 'A'),(12, 'D'),(5, 'M'),(6, 'B')]sorted_list = sorted(random_list, key=lambda x: x[1])

More on Dict/SetComprehensionmy_dict= {i: i** 2 for iin range(10)}my_set= {i** 2 for iin range(10)}Get dictionary keysmy_dict.keys()

Another way for legend

Scatter plot

quotesdbs_dbs12.pdfusesText_18
[PDF] python 3.7 documentation pdf

[PDF] python 7zip extract

[PDF] python add javascript to pdf

[PDF] python address parser

[PDF] python advanced oops concepts

[PDF] python analog vs digital filter

[PDF] python and mysql project

[PDF] python aws tutorial pdf

[PDF] python basics a practical introduction to python 3 free pdf

[PDF] python basics a practical introduction to python 3 real python

[PDF] python basics: a practical introduction to python 3

[PDF] python centrale supelec

[PDF] python class design best practices

[PDF] python class design example

[PDF] python class design patterns