id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
4,300 | def argument_test_natural_number( )def helper( )if type(xis int and return (xelseraise exception("argument is not an integer"return helper @argument_test_natural_number def factorial( )if = return elsereturn *factorial( - factorial( out[ ] in [ ]factorial(- exception traceback (most recent call lastin ---- factorial(- ... |
4,301 | sum_aritmetic_series( exception traceback (most recent call lastin ---- sum_aritmetic_series( in helper( return ( else---- raise exception("argument is not an integer" return helper exceptionargument is not an integer fixing the fibonacci series in [ ]def memoize( )memo {def helper( )if not in memomemo[nf(nreturn memo[... |
4,302 | built-in least-recently used cache decorator import functools @functools lru_cache(maxsize= typed=falsedef fib( )if return elsereturn fib( - fib( - static variables in [ ]exercise write decorator counting the number of times function was called the same but for varying number of parameters and keyword-arguments def cou... |
4,303 | next(iteroout[ ]'yin [ ]next(iteroout[ ]'tin [ ]next(iteroout[ ]'hin [ ]next(iteroout[ ]'oin [ ]next(iteroout[ ]'nin [ ]next(iterostopiteration traceback (most recent call lastin ---- next(iterostopiterationown generator in [ ]def abc_generator()yield "ayield "byield "cx abc_generator(we call like function function ret... |
4,304 | next(xstopiteration traceback (most recent call lastin ---- next(xstopiterationin [ ]print(next( )<-yield "aprint(next( )<-yield "bprint(next( )<-yield "cthis is co-process this function creates code waiting to be executedwhen we assign abc_generatorafter it reaches yieldit returns value and stops then next is position... |
4,305 | type(abc_generator()out[ ]generator in ]generate pi value pi/ / / / def pi_series()sum while truesum sum / yield *sum - runs forever we can break with counterbut it is not good idea for in pi_series()print(iin ]def firstn(gn)for in range( )yield next(gprint(list(firstn(pi_series() )) context manager is used to allocate... |
4,306 | for sciencfic compucngrapid development easyreadable syntax versacle tools for experimentacon/learning comprehensive libraries powerful features process data at near "nacve codespeeds excellent visualizacon packages comprehensive libraries |
4,307 | program interaccvely with ipython understand the basics of numpy and scipy efficiently compute with large arrays of data load and save data to/from files on disk use matplotlib to plot data take advantage of supercompucng resources with parallel compu ng know where to turn for more help with these topics |
4,308 | we are describing enthought python distribucon essencallypre--assembled compilacon of python numpyscipyother useful libraries free for academic usea basic version is free for non-commercial use your computersdepartmentsetc may have different version of python installed everything we will see today is open source in msi... |
4,309 | unix shell commands are indicated with the percent sign ipython interpreter commands have in/out labels neither sign indicates python code that should be entered into text file |
4,310 | powerful environment for interaccve work run as "ipythonfrom any terminal ----pylab opcon auto-loads numpysets up graphics for ploang inspect any object with "?or help( |
4,311 | build up workspace of objects and funccons full history access through out[]%recallup/down arrow keys %load%editor %run external files lots moretype %magic |
4,312 | numpy providesthe basic array and matrix data types efficient implementacons of low--level math operacons large library of high--level math funccons built from efficient primicves scipy providesa home for wide variety of open--source mathemaccal and sciencfic algorithms modules for opcmizaconsignal processinglinear alg... |
4,313 | array data type with vectorized operacons(similar to matlab or idlsupports same operacons as python list type except every element is of same data type so they can be stored in memory packed like arrays |
4,314 | here we are comparing "pure pythonloop to the equivalent in numpy |
4,315 | numpy arrays are rectangles in arbitrarily many dimensions -operate element--by-element for same--shape arrays |
4,316 | index notacon gives access to any "sliceof an array array slices can be assigned this changes the original array [ ,:,:copy(would avoid changing |
4,317 | numpy arrays have many useful built--in methods |
4,318 | and the numpy module provides more |
4,319 | vectorized logical operators indexing funccons output of index funccons can be used to slice arrays |
4,320 | vectorized logical operators indexing funccons output of index funccons can be used to slice arrays |
4,321 | numpy fft fftsforward/inverse -- and -- numpy random generate random numbersmany distribucons to choose from numpy matrix special arrays that obey matrix math numpy polynomial module for represencng and manipulacng arbitrary polynomials |
4,322 | matplotlib provides high--quality -- (and some --dploang display in window or output to pdfsvgpngetc implemented as modular object--oriented system pylab provides matlab--ish interaccve interface to matplotlib access with ipython ----pylab defaults to popping up plots in separate window |
4,323 | |
4,324 | these examples are from the matplotlib org examples seccon |
4,325 | |
4,326 | |
4,327 | |
4,328 | |
4,329 | clustering algorithms (scipy clusterintegracon and odes (scipy integrateinterpolacon (scipy interpolateinput and output (scipy iolinear algebra (scipy linalgmulc--dimensional image processing (scipy ndimageopcmizacon and root finding (scipy opcmizesignal processing (scipy signalsparse matrices (scipy sparsespacal algor... |
4,330 | most scipy roucnes use fast numpy low--level math operacons some scipy roucnes use highly opcmized external libraries scipy linalg links to blaslapack or mkl behind the scenes |
4,331 | chances are you want to load and save data numpy and scipy io offer variety of facilices |
4,332 | very common for smaller data setssimple columns of numbers numpy loadtxt(simple interfacegood defaults numpy genfromtxt(more complexhandles unusual formaangcommentsmissing valuesetc |
4,333 | numpy savetxt(write to columns of numbers |
4,334 | binary data is much more scalable smaller files on disk faster to load and save may be necessary to exchange data with other sopware scck to portable (machine--independentformats |
4,335 | numpy na ve format npynumpy load(and numpy save(or use numpy savez(to store many arrays in compressed npz fastportablebut mostly only supported by python scipy io matlab support for matlab matscipy io loadmat(and scipy io savemat(scipy io idl read (no saveidl sav files scipy io readsav( |
4,336 | many standard formats supported scipy io netcdf netcdf interface py exposes hdf api pytables is an excellent high--level interface to hdf pyfits for fits datasets etc |
4,337 | for big jobs you will eventually want to parallelize your code the python interpreter has trouble with mulcthreading mulc--process is usually best approach depends on the problem you need to solve |
4,338 | many jobs need to process lots of datadon' need to communicate amongst themselves somecmes called "embarrassingly parallelgnu parallel --- simple way to launch jobs launch one job for every file in dirline in fileetc can work with pbs on itasca to use many nodes |
4,339 | |
4,340 | -- should match ppn (unless you know what you're doingthis is processes per node will run one job per line of input on stdin or in argfile max of nodes ppn running at once see "man parallelfor more features |
4,341 | mpi "message passing interfaceenables parallel processes to communicate efficiently commonly one process will be "controllerand manage worker processes inherent support for scaser--gather operacons mpi is well--supported on our clusters mpi py interfaces to mpi from inside python caveat for mpi gurusnumpy does not have... |
4,342 | simple "hello worldscript |
4,343 | simple "hello worldscript |
4,344 | possible to pass numpy arrays like buffers |
4,345 | also works with (pickle--ablepython objects much slower than --based arraysbut very convenient |
4,346 | ipython notebook connect to ipython with browser for mathemacca--like notebook interface pycuda and pyopencl gpu compucng sympy mathemacca--style symbolic math databases are easy to connect to pythonor use advanced big data toolkit like pandas or pytables |
4,347 | exampleipython notebook with pylab and sympy notebook creates graphical log in browser sympysymbolic cas to try this |
4,348 | non-data descriptor __getattribute__ breaks the descriptor usage use more than one instance for testing examples conclusion more examples generalized attribute validation function decorators @property descriptors generalized validation summary inheritance with super super child before parent inherit __init__ inherit __... |
4,349 | python review introduction python is the programming language which can be used for various purposes web designmathematical modelingcreating documents and game designs etc in this we will review some of the basic features of python thenfrom next we will write some good coding styles with advance features of python note... |
4,350 | python (linuxor python (linuxor :\>python (in windowslisting hello world print("hello world"hello world print("hello % simulation can be done using % ("world""python")hello worldsimulation can be done using python running python files we can also save the code in python file with extension py'which can be run from pyth... |
4,351 | listing variables #variableex pya and are the variables which stores and respectively = = following line will add value of with print( + following line will perform ( + )/ print(( + )/ following line will perform ( + )/ and then display the interger value only print(int(( + )/ ) built-in object types table shows the va... |
4,352 | (continued from previous page octal' ois used before number print command shows the integer value print( #to see octal form use `octprint(oct( )# + imagenary print( #( + jprint(abs( )# round above value upto decimal =round(abs( ), print( # string string can be very useful for displaying some output messages on the scre... |
4,353 | listing list #listex py [ "as it is""abc" + jindex start with location of number is ' in the list print( [ ] print( [ ]abc #replace 'abcwith 'xyza[ ]='xyzprint( [ ]xyz add at the end of list append( print( [ 'as it is''abc'( + ) tuple tuple is similar to the list tuple consists of values separated by commas as shown in... |
4,354 | (continued from previous page print(mydict items()dict_items([( 'one')(' ''alphabet')]print(mydict keys()dict_keys([ ' ']print(mydict values()dict_values(['one''alphabet'] print(mydict[ ]#one print(mydict[' ']alphabet add key-value while creating the dictionary subjectdict {'py''python''np''numpy''sp':'scipy'print(subj... |
4,355 | (continued from previous page {:ddecimal print("{: }format(xzfill( ) number xtotal places {:ddecimal print("{: }format(xzfill( ) number xtotal places control structure in this sectionvarious simple python codes are shown to explain the control structures available in python if-else 'if-elsestatements are used to define... |
4,356 | (continued from previous page bye bye number is even will not be printed as 'ifcondition is not satisfied ''explanation listing an if statement is made up of the 'ifkeywordfollowed by the condition and colon (:at the endas shown in line alsothe line is indented which means it will execute only if the condition in line ... |
4,357 | code in listing can be written using if-else statement as show in listing listing if-else statement ifelse pyuse if-else to check even and odd nubmer "inputcommand takes input as string xint(input('enter the number:\ ') is used to calculate remainder if % == print("number is even"elseprint("number is odd" ''output- st ... |
4,358 | (continued from previous page output enter the number number is divisible by and thank you output enter the number number is divisible by only % thank you output enter the number number is not divisible by and % % thank you output enter the number number is divisible by only thank you ''explanation listing let' discuss... |
4,359 | (continued from previous page elif % == #check this if % is not zero print("number is divisible by only"elif % == #check this if % is not zero print("number is divisible by only"elseprint("number is not divisible by and "print(" % " % print(" % " % print("thank you"listing 'andand 'orlogic #orlogic pycheck divisibility... |
4,360 | then value of 'nis incremented by ' = 'nis still less than therefore loop will be executed again in this iteration value of 'nwill become which is still less than in the same mannerloop will continue to increase the value of 'nuntil ' = when ' = 'then loop condition at line ' will not be satisfied and loop will not be ... |
4,361 | (continued from previous page numbers in forward order final value of is numbers in reverse order final value of is '' fruits=["apple""banana""orange"print("list of fruits are shown below:"for in fruitsprint( ''list of fruits are shown belowapple banana orange ''explanation listing at line ' 'command 'range( )generates... |
4,362 | in pythonfunction is defined using keyword 'defline defines the function with name 'addtwonumwhich takes two parameter and line add the values of 'aand 'band stores the result in variable 'sumfinally line returns the value to function call which is done at line in line function 'addtwonumis called with two values ' and... |
4,363 | (continued from previous page np linspacedevide line from to *pi into equidistant points np linspace( *np pi sinx np sin(xfind sin(xfor above points plt plot( ,sinxplot (xsin( )plt xlabel("time"label for axis plt ylabel("amplitude"label for axis plt title('sine wave'title plt xlim([ *np pi] -axis display range plt ylim... |
4,364 | listing arange arangeex py import numpy as np =np arange( , last element is not included in result print( [ print( shape( , total entries =np arange( , , print to with the spacing of print( [ print( shape( , total entries =np arange( - last element is not included in result self print( [ array multidimensional array ca... |
4,365 | (continued from previous page from scipy linalg import lu anp mat(' 'define matrix print(np shape( )( at np transpose(atranspose of matrix 'aprint(np shape(at)( eye(nis used for (nxnidentity matrix = *np eye( identity matrix print(np shape( )( * print(np shape( )( llu(aprint(llisting lu factorization of matrix scipyex ... |
4,366 | (continued from previous page - ] type of [ ] type of after np mat [ ]'' good practices as oppose to other programming languagespython provides various ways to iterate over the listwhich are shown in this section avoid range command multiply to all elements of arr arr [ bad practice for in range(len(arr))print( *arr[ ]... |
4,367 | loop in sorted order multiply to all elements of arrbut in sorted order arr [ for in sorted(arr)print( * in reversed sorted order for in sorted(arrreverse=true)print( * loop over keys dc 'toy': 'play': 'games': print keys of dictionaries for in dcprint(dloop over keys and values dc 'toy': 'play': 'games': print keysval... |
4,368 | (continued from previous pagebelow line will go in infinite loop for in animalsfor in amif len( animals append(aprint(animalsor we can use 'animals[:]in the for loopinstead of 'animalas shown belowloopupdate py animals ['tiger''cat''dog'for in animals[:]if len( animals append(aprint(animalscheck items in the list the '... |
4,369 | (continued from previous pagec ['five''six'update variables xyz yzx print(xyz object oriented programming object oriented programming (oopincreases the re-usability of the code alsothe codes become more manageable than non-oop methods butit takes proper planningand therefore longer timeto write the codes using oop meth... |
4,370 | the object 'jcan now use the function 'welcomemessageusing operatoras shown in line also'selfis used at line which is discussed in section section listing add function to class #ex py #class declaration class jungledef welcomemessage(self)print("welcome to the jungle" create object of class jungle jungle( welcomemessag... |
4,371 | listing constructor with default values #ex py #class declaration class jungle#constructor with default values def __init__(selfname="unknown")self visitorname name def welcomemessage(self)print("hello % welcome to the jungleself visitorname create object of class jungle jungle("meher" welcomemessage(hello meherwelcome... |
4,372 | warningherewe kept the class and main function in separate files it is not good idea keep these small related-codes separate like this we will learn to manage the code as we will write some big codes in the tutorial listing save classes in separate file #junglebook py #class declaration class jungle#constructor with de... |
4,373 | (continued from previous page print("hello % welcome to the jungleself visitorname class ratejungle(jungle)def __init__(selfnamefeedback)feedback ( - is the best self feedback feedback public attribute inheriting the constructor of the class super(__init__(name using parent class attribute visitorname def printrating(s... |
4,374 | listing polymorphismmove function works in different ways for different class-objects #main py #import class 'animalbirdfrom scarysound py from scarysound import animalbird def main()create objects of animal and bird class animal( bird( polymorphism scarysound(animals are running away due to scary sound scarysound(bird... |
4,375 | listing abstract methods are compulsory to define in childclass #scarysound py from junglebook import jungle class animal(jungle)def scarysound(self)print("animals are running away due to scary sound " class bird(jungle)def scarysound(self)print("birds are flying away due to scary sound " since jungle is defined as met... |
4,376 | (continued from previous page #class declaration class jungle#constructor with default values def __init__(selfname="unknown")self visitorname name def welcomemessage(self)print("hello % welcome to the jungleself visitorname class ratejungledef __init__(selffeedback)feedback ( - is the best self feedback feedback publi... |
4,377 | (continued from previous page #access to private attribute is not allowed #uncomment following line to see error print("jungle guide rating " __jungleguiderating #private attribute can still be accessed as below#objectname _classname __attributename print ("guide rating " _ratejungle__jungleguideratingguide rating stan... |
4,378 | (continued from previous page def printrating(self)print("thanks % for your feedbackself _visitorname class testdef __init__(self)inheritance is not required for accessing class attribute print("sum_of_feedback (jungle class attribute"jungle sum_of_feedbackprint("total_num_feedback (ratejungle class attribute"ratejungl... |
4,379 | (continued from previous page def __del__(self)student totalstudent - print("total students (del"self totalstudent def main() student("meher"total students (init student("krishna"total students (init student("patel"total students (init #delete object del total students (del print( nameerror because object is deleted pr... |
4,380 | listing __call__ method is executed when object is used as function callex py #class declaration class calculatepricediscount in def __init__(selfdiscount)self discount discount def __call__(selfprice)discountprice price price*self discount/ return (pricediscountprice def main()create object of class calculateprice wit... |
4,381 | (continued from previous page print( __dict__{'ispet''no''animal''lion' print(jungle __dict__""{'__doc__''__doc__'list of animal and pet information \ animal string\ ispet string\ ''__weakref__''__module__''__main__''__dict__''__init__'"" print(jungle __doc__"""list of animal and pet information animal string ispet str... |
4,382 | (continued from previous page studentid(- "krishna" ""traceback (most recent call last)raise typeerror("id must be positive integer""" studentid( "krishna" print( ids firstnames age krishna #uncomment below line to see the "attributeerrorgenerated by 'getattrprint( lastnamefollowing message will be displayed ""tracebac... |
4,383 | virtual environmentpackage and distribution anadconda virtual environment installation go to anaconda webpage and download the latest python version for your os ( linux or windowswindowsdouble click the downloaded exe file to install the anaconda during installationit will ask to include the anaconda in the environment... |
4,384 | (continued from previous pageproceed ([ ]/ ) downloading and extracting packages wincertstore- kb #####################################################################'-##### pip mb #####################################################################'-##### wheel kb ####################################################... |
4,385 | (continued from previous pagedownloading da bcda ff cfe fb /wget- zip building wheels for collected packageswget running setup py bdist_wheel for wget done stored in directory'- :\users\meherp\appdata\local\pip\cache\wheels\ \ \ \ cea db fea ecb ef successfully built wget installing collected packageswget successfully ... |
4,386 | (myenvc:\users\meherp>pip install - :\users\meherp\desktop\myenv txt installing collected packagesitsdangerousmarkupsafejinja clickwerkzeugflasksqlparsepytz'-django successfully installed jinja markupsafewerkzeugclick- djangoflask- '-itsdangerouspytz- sqlparsesee the list of installed libraries'freezecommand is used fo... |
4,387 | modify bashrc add below line at the end of bashrc file if virtual environment is installed in the anaconda environment replace /home/meherp/anaconda with correct installation location virtualenv and virtualenvwrapper export workon_home=$homevirtualenvs export virtualenvwrapper_python=/home/meherp/anaconda /bin/python s... |
4,388 | (pythondsppython import sys sys path '/home/pythondsp/lib/python /site-packages'create files in this sectionwe will write some python codesand then in next sectionwe will convert these python modules into package activate the environmentand create folder with any name 'bucketat desired location (pythondspmkdir - ~/desk... |
4,389 | (continued from previous pageimport my_work import my_work packages in this sectionwe will convert the python modules into the package notepackage name should be uniqueso that it will not collide with other package names create another folder inside the folder 'bucketwith any desired name 'wolfpack'and move the 'python... |
4,390 | bucket/wolfpack/my_work py from my_calc import sum numdiff num print("{ { { }format(xysum num(xy))print("{ { { }format(xydiff num(xy))close the python terminal and open it again then execute the commands and it will work fine(pythondsppython from wolfpack import my_work warningnowthe folder 'wolfpackis 'packageand the ... |
4,391 | from wolfpack my_calc import sum numcurrentlywe have only two files in the package therefore it' easy to import 'functionlike this butif we have files with folders in packagethen it will be difficult/inconvenient to remember the import-location of the 'methodsa better approach is to to use the '__init__ pyfile as shown... |
4,392 | (continued from previous page my_calc diff num( diff num( traceback (most recent call last)file ""line in nameerrorname 'diff numis not defined distribute the package in this sectionwe will convert our package to 'distributable package'which can be used by others as wellnotewe need to create the setup py file inside th... |
4,393 | (pythondsppython setup py sdist running sdist running check warningcheckmissing required meta-dataurl warningcheckmissing meta-dataeither (author and author_emailor (maintainer and maintainer_email'-must be supplied warningsdistmanifest template 'manifest indoes not exist (using default file listwarningsdiststandard fi... |
4,394 | debugging introdution in this the 'sysmodule is discussed to read the input from the terminal then little overview of the debugging tool is providedwhich will be used in subsequent first code in the below codeperimeter and area of circular ring is calculated ring py from math import pi metal "copperradius perimeter *pi... |
4,395 | the 'sys argvpass the command line argument to python script the argv[ is the file name alsothe arguments are passed as string-formattherefore these need to be converted into proper formatas done in line where the argv[ is converted into 'floatformat ring py import sys from math import pi if len(sys argv! display error... |
4,396 | (continued from previous pageprint(metalgold python debugger (pdbanother way to debug the code is to use the 'pdb'as shown belowherepython debugger module is imported at line nextpdb set_trace is used to set the starting location for the debuggingi the code will stop after reaching this point line here ring py import p... |
4,397 | conclusion in this we saw the debugging tools which will be used in subsequent alsothe module 'sysis discussed for reading the inputs from the terminal conclusion |
4,398 | print statement introduction in this the print statement is discussed to print the output in nice format expansion calculation in the below codenumber of days are calculate in which the diameter of the ring becomes greater than or equal to cm expansion py find the number of days when radius cm due to heat-expansion imp... |
4,399 | (continued from previous page radius +expansion day + increment the number of days by one print the number of days print("number of days ="dayfollowing are the outputs for different metals with same radiuspython expansion py "gold number of days python expansion py "iron number of days python expansion py "copper numbe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.