id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
3,700 | outline some examples of pytorch syntax the main oo concepts pre-defined and programmer-supplied attributes function objects vs callables defining class in python how python creates an instance defining methods creating class hierarchy multiple-inheritance class hierarchies making class instance iterable purdue univers... |
3,701 | the syntax for defining method method defined for class must have special syntax that reserves the first parameter for the object on which the method is invoked this parameter is typically named self for instance methodsbut could be any legal python identifier in the script shown on the next slidewhen we invoke the con... |
3,702 | defining method (contd in the definition shown belowone would think that function like baz(in the script below could be called using the syntax baz()but that does not work (we will see later how to define class method in pythonclass class xdef __init__(selfnn)self nn def getn(self)return self def foo(self,arg ,arg ,arg... |
3,703 | method can be defined outside class it is not necessary for the body of method to be enclosed by class function object created outside class can be assigned to name inside the class the name will acquire the function object as its binding subsequentlythat name can be used in method call as if the method had been define... |
3,704 | method defined outside class (contd def bar(self,arg ,arg arg = )self arg arg arg class class xfoo bar def __init__(selfnn)self nn def getn(self)return self #--end of class definition ---xobj ( printxobj getn(xobj foo printxobj getn(purdue university |
3,705 | only one method for given name rule when the python compiler digests method definitionit creates function binding for the name of the method for examplefor the following code fragment class xdef foo(selfarg arg )implemention_of_foo rest_of_class_x the compiler will introduce the name foo as key in the namespace diction... |
3,706 | only one method per name rule (contd so if you examine the attribute dict after the class is compiledyou will see the following sort of entry in the namespace dictionary for 'foosince all the method names are stored as keys in the namespace dictionary and since the dictionary keys must be uniquethis implies that there ... |
3,707 | method names can be usurped by data attribute names we just talked about how there can only be one method of given name in class -regardless of the number of arguments taken by the method definitions as more general case of the same propertya class can have only one attribute of given name what that means is that if cl... |
3,708 | destruction of instance objects python comes with an automatic garbage collector each object created is kept track of through reference counting each time an object is assigned to variableits reference count goes up by onesignifying the fact that there is one more variable holding reference to the object and each time ... |
3,709 | encapsulation issues for classes encapsulation is one of the cornerstones of oo how does it work in pythonas opposed to oo in +and javaall of the attributes defined for class are available to all in python so the language depends on programmer coopration if software requirementssuch as those imposed by code maintenance... |
3,710 | defining static attributes for class class definition usually includes two different kinds of attributesthose that exist on per-instance basis and those that exist on per-class basis the latter are commonly referred to as being static variable becomes static if it is declared outside of any method in class definition f... |
3,711 | static attributes (contd class robot class robotnext_serial_num def __init__(selfan_owner)self owner an_owner self idnum self get_next_idnum(def get_next_idnumself )new_idnum robot next_serial_num robot next_serial_num + return new_idnum def get_owner(self)return self owner def get_idnum(self)return self idnum end of c... |
3,712 | static methods in the old daysa static method used to be created by supplying function object to staticmethod(as its argument for exampleto make method called foo(staticwe' do the following def foo()print(''foo called''foo staticmethodfoo the function object returned by staticmethod(is static in the above examplewhen f... |
3,713 | outline some examples of pytorch syntax the main oo concepts pre-defined and programmer-supplied attributes function objects vs callables defining class in python how python creates an instance defining methods creating class hierarchy multiple-inheritance class hierarchies making class instance iterable purdue univers... |
3,714 | extending class -using super(in method definitions method extension for the case of single-inheritance is illustrated in the employee-manager class hierarchy shown on slide note how the derived-class promote(calls the base-class promote()and how the derived-class myprint(calls the base-class myprint(as you will see lat... |
3,715 | method definitions in derived class calling superclass definition directly the next two slides show single inheritance hierarchywith employee as the base class and the manager as the derived class we want both the promote(and the myprint(methods of the derived class to call on the method of the same names in the base c... |
3,716 | calling superclass method definition directly base class employee class employeedef __init__(selfnampos)self name nam self position pos promotion_table 'shop_floor'staff''staff'manager''manager'executuvedef promote(self)self position employee promotion_table[self positiondef myprint(self)printself name"%sself positione... |
3,717 | calling superclass method definition directly (contd (continued from previous slidetest code emp employee("orpheus""staff"emp myprint(orpheus staff emp promote(printemp position manager emp myprint(orpheus manager man manager("zaphod""manager""sales"man myprint(man promote(printman position executive print(isinstance(m... |
3,718 | method definition in derived class calling super(for the parent class' method shown on the next slide is the same class single-inheritance class hierarchy you saw on the previous slides and the methods of the derived class still want part of the job to be done by the methods of the parent class but now the methods of t... |
3,719 | method definition in derived class calling super(for the parent class' method (contd base class employee class employeedef __init__(selfnampos)self name nam self position pos promotion_table 'shop_floor'staff''staff'manager''manager'executuvedef promote(self)self position employee promotion_table[self positiondef mypri... |
3,720 | derived class constructor calling base class' constructor directly the point of this slide is to emphasize what you might have noticed already in the employee-manager class hierarchythe first thing that the constructor of derived class must do is to call on the constructor of the base class for the initializations that... |
3,721 | derived class constructor calls base class constructor directly (contd base class employee class employeedef __init__(selfnampos)self name nam self position pos promotion_table 'shop_floor'staff''staff'manager''manager'executuvedef promote(self)self position employee promotion_table[self positiondef myprint(self)prints... |
3,722 | derived class constructor calling base class constructor through super(as shown on the next slideanother way for derived class constructor to call on the constructor of the base class is using the built-in super(as shown on the next slide note in line (athe following syntax for the call to super()super(managerself__ini... |
3,723 | derived class constructor calling base class constructor through super((contd base class employee class employeedef __init__(selfnampos)self name nam self position pos promotion_table 'shop_floor'staff''staff'manager''manager'executuvedef promote(self)self position employee promotion_table[self positiondef myprint(self... |
3,724 | new style syntax for calling super(in derived-class constructor howeverpython allows derived class' constructor to call super(without using the derived class' name as its argument shown on the next slide is the same hierarchy that you saw on the previous slidebut with the following new-style syntax for the call to supe... |
3,725 | new style syntax for calling super(in derived-class constructor (contd base class employee class employeedef __init__(selfnampos)self name nam self position pos promotion_table 'shop_floor'staff''staff'manager''manager'executuvedef promote(self)self position employee promotion_table[self positiondef myprint(self)prints... |
3,726 | outline some examples of pytorch syntax the main oo concepts pre-defined and programmer-supplied attributes function objects vs callables defining class in python how python creates an instance defining methods creating class hierarchy multiple-inheritance class hierarchies making class instance iterable purdue univers... |
3,727 | an example of diamond inheritance python allows class to be derived from multiple base classes in generalthe header of such derived class would look like class derived_classbase base base )body of the derived class the example shown on the next slide contains diamond hierarchy for illustrating multiple inheritance the ... |
3,728 | an example of diamond inheritance (contd classes of abcd of the hierarchy class (object)def __init__(self)print("called ' init"class ba )def __init__(self)print("called ' init"super(__init__(class ca )def __init__(self)print("called ' init"super(__init__(class ( , )def __init__(self)print("called ' init"super(__init__(... |
3,729 | on the importance of using super(in init (in order to illustrate the importance of using super() will present good-practice and bad-practice scenarios when defining multiple-inheritance hierarchy the example shown on the previous slide represented good-practice scenario in which we called the parent class' in the defin... |
3,730 | importance of using super(in classes of abc of the original hierarchy class (object)def __init__(self)print("called ' init"init ((contd class ba )def __init__(self)print("called ' init"super( ,self__init__(class ca )def __init__(self)print("called ' init"super( ,self__init__( client wants to mixin additional behaviors ... |
3,731 | new-style version of the good-practice example of using super in init (the example shown on the next slide is basically the same as what was shown in the previous slidea good-practice scenario in which the original programmer of the abc hierarchy has used the new-style super(to call the parent class' init (in the init ... |
3,732 | new-style version of the good practice example (contd classes abc of the orignal hierarchy class (object)def __init__(self)print("called ' init"class ba )def __init__(self)print("called ' init"super(__init__(class ca )def __init__(self)print("called ' init"super(__init__(the mixin class and the mixin versions of the an... |
3,733 | consequences of not using super(what' shown on the next slide represents bad-practice scenario in which the original programmer has explicitly called the parent class' init (in the definition of init (for the derived class subsequentlya client of the abcd hierarchy decides to extend the abc hierarchy because he/she wan... |
3,734 | consequences of not using super()(contd classes of abc of the hierarchy class (object)def __init__(self)print("called ' init"class ba )def __init__(self)print("called ' init" __init__(selfclass ca )def __init__(self)print("called ' init"super( ,self__init__(class ( , )def __init__(self)print("called ' init"super( ,self... |
3,735 | outline some examples of pytorch syntax the main oo concepts pre-defined and programmer-supplied attributes function objects vs callables defining class in python how python creates an instance defining methods creating class hierarchy multiple-inheritance class hierarchies making class instance iterable purdue univers... |
3,736 | iterable vs iterator class instance is iterable if you can loop over the data stored in the instance the data may be stored in the different attributes and in ways not directly accessible bysayarray like indexing class must provide for an iterator in order for its instances to be iterable and this iterable must be retu... |
3,737 | computingin the sense of doing mathematical calculationsis skill that mankind has developed over thousands of years programmingon the other handis in its infancywith history that spans few decades only both topics are vastly comprehensive and usually taught as separate subjects in educational institutions around the wo... |
3,738 | preface it is easy to use excellent ready-made software the wrong way insight in programming and the mathematics behind is fundamental for understanding complex softwareavoiding pitfallsand become safe user bugs (errors in computer codeare present in most larger computer programs (also in the ones from the shop!what do... |
3,739 | vii target audience and background knowledge this book was written for studentsteachersengineers and scientists that know nothing about programming and numerical methods from beforebut who seek minimum of the fundamental skills required to get started with programming as tool for solving scientific and engineering prob... |
3,740 | preface shift in popularity from these compiled languages to more high-level and easier-toread languages like matlabpythonrmaplemathematicaand idlfor instance this latter class of languages is computationally less efficientbut superior with respect to overall human problem solving efficiency this book emphasizes how to... |
3,741 | ix supplementary materials all program and data files referred to in this book are available from the book' primary web siteacknowledgments first of allwe want to thank all students who attended the courses fm modelling and simulation of dynamic systemsfm scientific computingfb mathematics and fb physics at the univers... |
3,742 | the first few steps what is programand what is programming python program with variables the program dissection of the program why not just use pocket calculatorwhy you must use text editor to write programs installation of python write and run your first program python program with library function python program with... |
3,743 | contents computing integrals basic ideas of numerical integration the composite trapezoidal rule the general formula implementation making module alternative flat special-purpose implementation the composite midpoint method the general formula implementation comparing the trapezoidal and the midpoint methods testing pr... |
3,744 | xiii magic fix of the numerical method the nd-order runge-kutta method (or heun' method software for solving odes the th-order runge-kutta method more effectsdampingnonlinearityand external forces illustration of linear damping illustration of linear damping with sinusoidal excitation spring-mass system with sliding fr... |
3,745 | contents the need for text editor text editors terminal windows using plain text editor and terminal window spyder the sagemathcloud and wakari web services basic intro to sagemathcloud basic intro to wakari installing your own python packages writing ipython notebooks simple program in the notebook mixing textmathemat... |
3,746 | exercise error messages exercise volume of cube exercise area and circumference of circle exercise volumes of three cubes exercise average of integers exercise interactive computing of volume and area exercise peculiar results from division exercise update variable at command prompt exercise formatted print to screen e... |
3,747 | list of exercises exercise explore rounding errors with large numbers exercise write test functions for xdx exercise rectangle methods exercise adaptive integration exercise integrating raised to exercise integrate products of sine functions exercise revisit fit of sines to function exercise derive the trapezoidal rule... |
3,748 | the first few steps what is programand what is programmingtodaymost people are experienced with computer programstypically programs such as wordexcelpowerpointinternet explorerand photoshop the interaction with such programs is usually quite simple and intuitiveyou click on buttonspull down menus and select operationsd... |
3,749 | the first few steps may want to analyze these data in excel and make some graphics out of it howeverassume there is no menu in excel that allows you to import data in this specific format excel can work with many different data formatsbut not this one you start searching for alternatives to excel that can do the same a... |
3,750 | arguments to other functionsthere is good support for interfacing cc+and fortran code ( python program may use code written in other languages)and functions explicitly written for scalar input often work fine (without modificationalso with vector input another important thingis that python is available for free it can ... |
3,751 | the first few steps the program let us next look at python program for evaluating this simple formula assume the program is contained as text in file named ball py the text looks as follows (file ball py)program for computing the height of ball in vertical motion initial velocity acceleration of gravity time * * * ** v... |
3,752 | the sign it takes the rest of the line as comment python then simply skips reading the rest of the line and jumps to the next line in the codeyou see several such comments and probably realize that they make it easier for you to understand (or guesswhat is meant with the code in simple casescomments are probably not mu... |
3,753 | the first few steps for every milli-second of the flightall that punching on the calculator would have taken you something like four hoursif you know how to programhoweveryou could modify the code above slightlyusing minute or two of writingand easily get all the positions computed in one go within second much stronger... |
3,754 | python program with library function but first warningthere are many things that must come together in the right way for ball py to run correctly on your computer there might be problems with your python installationwith your writing of the program (it is very easy to introduce errors!)or with the location of the filej... |
3,755 | the first few steps / as input parameter or argument the atan function takes one argumentand the computed value is returned from atan this means that where we see atan( / ) computation is performed (tan = /and the result "replacesthe text atan( /xthis is actually no more magic than if we had written just /xthen the com... |
3,756 | we will often use this import statement and then get access to all common mathematical functions this latter statement is inserted in program named ball_angle pyfrom math import horizontal position vertical position angle atan( /xprint (angle/pi)* this program runs perfectly and produces as outputas it should at firsti... |
3,757 | the first few steps this program produces plot of the vertical position with timeas seen in figure as you noticethe code lines from the ball py program in have not changed muchbut the height is now computed and plotted for thousand points in timelet us take look at the differences between the new program and our previo... |
3,758 | fig plot generated by the script ball_plot py showing the vertical position of the ball at thousand points in time and ending with stop the expression linspace( creates coordinates between and (including both and the mathematically inclined reader will notice that coordinates correspond to equal-sized intervals in oe a... |
3,759 | the first few steps more basic concepts so far we have seen few basic examples on how to apply python programming to solve mathematical problems before we can go on with other and more realistic exampleswe need to briefly treat some topics that will be frequently required in later these topics include computer science ... |
3,760 | sometimes you would like to repeat command you have given earlieror perhaps give command that is almost the same as an earlier one then you can use the up-arrow key pressing this one time gives you the previous commandpressing two times gives you the command before thatand so on with the down-arrow key you can go forwa... |
3,761 | the first few steps variable (the word float is just computer language for real numberin any casepython thinks of as an objectof type int or float another common type of variable is stri stringneeded when you want to store text when python interprets "this is string"it stores the text (in between the quotesin the varia... |
3,762 | in [ ] / out [ ] in [ ]out [ ] we see two alternative ways of writing itbut only the last way of writing it gave the correct ( expectedresultwhywith python version the first alternative gives what is called integer divisioni all decimals in the answer are disregardedso the result is rounded down to the nearest integer ... |
3,763 | the first few steps real integer string 'some messageprint 'real= finteger=%dstring=% (realintegerstringprint 'real=% einteger=% dstring=% (realintegerstringthe output of print is stringspecified in terms of text and set of variables to be inserted in the text variables are inserted in the text at places indicated by a... |
3,764 | aligned under each other and written with the same precision the output then becomes formatting via printf syntax we shall frequently use the printf syntax throughout the book so there will be plenty of further examples the modern alternative to printf syntax modern python favors the new format string syntax over print... |
3,765 | the first few steps " of zero( [ ])" of one( [ ])and so on the very first line in the example abovei zeros( instructs python to reserveor allocatespace in memory for an array with four elements and initial values set to the next four lines overwrite the zeros with the desired numbers (measured heights)one number for ea... |
3,766 | fig generated plot for the heights of family members from two families from numpy import zeros import matplotlib pyplot as plt zeros( [ [ [ [ zeros( [ [ [ [ family_member_no zeros( family_member_no[ family_member_no[ family_member_no[ family_member_no[ plt plot(family_member_nohfamily_member_nohplt xlabel('family membe... |
3,767 | the first few steps then you could (in principledo lot of other things in your codebefore you plot the second curve by plt plot(family_member_nohplt hold('off'notice the use of hold here hold('on'tells python to plot also the following curve(sin the same window python does so until it reads hold('off'if you do not use ... |
3,768 | plt savefig('some_plot png'plt savefig('some_plot pdf'plt savefig('some_plot jpg'plt savefig('some_plot eps'png format pdf format jpg format encanspulated postscript format for the reader who is into linear algebrait may be useful to know that standard matrix/vector operations are straightforward with arrayse matrix-ve... |
3,769 | the first few steps you try to run the program to see what python' response is then you know what the problem is and understand what the error message is about this will greatly help you when you get similar error message or warning later very oftenyou will experience that there are errors in the program you have writt... |
3,770 | as the answer usually involves extensive knowledge of the application area we will therefore limit our testing to the verification part input data computer programs need set of input data and the purpose is to use these data to compute output datai results in the previous program we have specified input data in terms o... |
3,771 | the first few steps from sympy import xy symbols(' ' * print which causes the symbolic result * to appear on the screen note that no numerical value was assigned to any of the variables in the symbolic computation only the symbols were usedas when you do symbolic mathematics by hand on piece of paper symbolic computati... |
3,772 | limit(sin( )/xx solve( * xwolframalpha is very flexible with respect to syntax another impressive tool for symbolic computations is sage which is very comprehensive package with the aim of "creating viable free open source alternative to magmamaplemathematica and matlabsage is implemented in python projects with extens... |
3,773 | the first few steps comments on constructions that are fast or slowbut the main focus of this book is to teach how to write correct programsnot the fastest possible programs deleting data no longer in use python has automatic garbage collectionmeaning that there is no need to delete variables (or objectsthat are no lon... |
3,774 | exercise volume of cube write program that computes the volume of cube with sides of length cm and prints the result to the screen both and should be defined as separate variables in the program run the program and confirm that the correct result is printed hint see ball py in the text filenamecube_volume py exercise a... |
3,775 | the first few steps exercise peculiar results from division consider the following interactive python sessionin [ ] = = in [ ] / out[ ] what is the problem and how can you fix itexercise update variable at command prompt invoke python interactively and perform the following steps initialize variable to add to print out... |
3,776 | basic constructions if testscolon and indentation very often in lifeand in computer programsthe next action depends on the outcome of question starting with "ifthis gives the possibility to branch into different types of action depending on some criterion let us as usual focus on specific examplewhich is the core of so... |
3,777 | basic constructions hold the coordinates of point and let be the length of the move pseudo code ( not "realcodejust "sketch of the logic"then goes like random number in [ , if < move northy else if < move eastx else if < move southy else if < move westx note the need for first asking about the value of and then perform... |
3,778 | >given the assignment to tempyou should go through each boolean expression below and determine if it is true or false temp temp = temp ! temp temp temp < temp > assign value to variable temp equal to temp not equal to temp less than temp greater than temp less than or equal to temp greater than or equal to functions fu... |
3,779 | basic constructions will be understood by python as first compute the expressionthen send the result back ( returnto where the function was called from both def and return are reserved words the function depends on ti one variable (or we say that it takes one argument or input parameter)the value of which must be provi... |
3,780 | one single return statement be prepared for critical comments if you return wherever you want an expression you will often encounter when dealing with programmingis main programor that some code is in main this is nothing particular to pythonand simply refers to that part of the program which is outside functions howev... |
3,781 | basic constructions notice the two return values which are simply separated by comma when calling the function (and printing)arguments must appear in the same order as in the function definition we would then write print xy(initial_x_velocityinitial_y_velocitytimethe two returned values from the function could alternat... |
3,782 | fault value in scriptthe function xy may now be called in many different ways for exampleprint xy( would make xy perform the computations with and the default values ( zeroof and the two numbers returned from xy are printed to the screen if we wanted to use another initial value for ywe coulde write print xy( , = which... |
3,783 | basic constructions when runthis program first prints the sum of and ( )and then it prints the product ( we see that treat_xy takes function name as its first parameter inside treat_xythat function is used to actually call the function that was given as input parameter thereforeas shownwe may call treat_xy with either ... |
3,784 | we notice that there is some overhead in function calls the impact of the overhead reduces quickly with the amount of computational work inside the function for loops many computations are repetitive by nature and programming languages have certain loop structures to deal with this here we will present what is referred... |
3,785 | basic constructions is then used (combined with the starting at thuscalling rangefor exampleas range( would return the integers note that decreasing integers may be produced by letting start stop combined with negative step this makes it easy toe traverse arrays in either direction let us modify ball_plot py from sect ... |
3,786 | will contain the largest number from the array when you run the programyou get the largest height achieved was which compares favorably to the plot that pops up to implement the traversing of arrays with loops and indicesis sometimes challenging to get right you need to understand the startstop and step length choices ... |
3,787 | basic constructions for in range( + ) + * print executing this code will print the number to the screen note in particular how the accumulation variable is initialized to zero the value of then gets updated with each iteration of the loopand not until the loop is finished will have the correct value this way of buildin... |
3,788 | if you type and run this program you should get = at the new thing here is the while loop only the loop (note colon and indentationwill run as long as the boolean expression [ evaluates to true note that the programmer introduced variable (the loop indexby the name iinitialized it ( before the loopand updated it ( + in... |
3,789 | basic constructions list may also be created by simply writinge ['hello' giving list where [ contains the string hellox[ contains the integer etc we may add and/or delete elements anywhere in the list as shown in the following example ['hello' insert( - then becomes [- 'hello' del [ then becomes [- 'hello' append( then... |
3,790 | in some casesit is required to run through (or morelists at the same time python has handy function called zip for this purpose an example of how to use zip is provided in the code file_handling py below we should also briefly mention about tupleswhich are very much like liststhe main difference being that tuples canno... |
3,791 | basic constructions transform coordinates from math import log def ( )return log(yfor in range(len( )) [if( [ ]write out and to two-column file filename 'tmp_out datoutfile open(filename' 'open file for writing outfile write(' and coordinates\ 'for xiyi in zip(xy)outfile write('% % \ (xiyi)outfile close(such file with ... |
3,792 | exercises cnow let the statement inside the function have an indent of three spaces (while the remaining two lines of the function have fourdremove the left parenthesis in the first statement def ( )echange the first line of the function definition from def ( )to def (): remove the parameter fchange the first occurrenc... |
3,793 | basic constructions the vertices ("corners"of the polygon have coordinates / /:xn yn /numbered either in clockwise or counter clockwise fashion the area of the polygon can amazingly be computed by just knowing the boundary coordinates xn yn xn yn xn yn / write function polyarea(xythat takes two coordinate arrays with t... |
3,794 | exercises exercise while loop with errors assume some program has been written for the task of adding all integers some_number while some_number + print some_number aidentify the errors in the program by just reading the code and simulating the program by hand bwrite new version of the program with errors corrected run... |
3,795 | basic constructions exercise compute up through historygreat minds have developed different computational schemes for the number we will here consider two such schemesone by leibniz ( )and one by euler ( the scheme by leibniz may be written kd while one form of the euler scheme may appear as dt kd if only the first ter... |
3,796 | exercises cgenerate all the combinations of throwing two dice (the number of eyes can vary from to count how many combinations where the sum of the eyes equals filenamecombine_sets py exercise frequency of random numbers write program that takes positive integer as input and then draws random integers in the interval o... |
3,797 | basic constructions bwrite another function with loop where the user is asked for time on the interval oe and the corresponding (interpolatedy value is written to the screen the loop is terminated when the user gives negative time cuse the following measurements : : : : : corresponding to times (min)and compute interpo... |
3,798 | exercises exercise fit sines to straight line lot of technologyespecially most types of digital audio devices for processing soundis based on representing signal of time as sum of sine functions say the signal is some function ton the interval oe( more general interval oeabcan easily be treatedbut leads to slightly mor... |
3,799 | basic constructions fchoose tto be straight line td on oecall trial( and try to find through experimentation some values and such that the sum of sines sn tis good approximation to the straight line gnow we shall try to automate the procedure in fwrite function that has three nested loops over values of and let each lo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.