id
int64
0
25.6k
text
stringlengths
0
4.59k
6,100
to use the techniques shown in this file to reuse any python class of coursethis example could be more complex in practice as mentioned earlieryou generally need to check the return value of every python api call to make sure it didn' fail the module import call in this codefor instancecan fail easily if the module isn' on the search pathif you don' trap the null pointer resultyour program will almost certainly crash when it tries to use the pointer (at least eventuallyexample - is recoding of example - with full error-checkingit' bigbut it' robust example - pp \integrate\embed\pyclasss\objects-err #include #include #define error(msgdo printf("% \ "msg)exit( )while ( main(/run objects with low-level calls and full error checking *char *arg ="sir"*arg ="robin"*cstrpyobject *pmod*pclass*pargs*pinst*pmeth*pres/instance module klass(*py_initialize()pmod pyimport_importmodule("module")if (pmod =nullerror("can' load module")pclass pyobject_getattrstring(pmod"klass")py_decref(pmod)if (pclass =nullerror("can' get module klass")pargs py_buildvalue("()")if (pargs =nullpy_decref(pclass)error("can' build arguments list")pinst pyeval_callobject(pclasspargs)py_decref(pclass)py_decref(pargs)if (pinst =nullerror("error calling module klass()")/fetch module */fetch module class */call class(*/result instance method( , *pmeth pyobject_getattrstring(pinst"method")/fetch bound method *py_decref(pinst)if (pmeth =nullerror("can' fetch klass method")pargs py_buildvalue("(ss)"arg arg )if (pargs =nullpy_decref(pmeth)error("can' build arguments list")/convert to python *using python classes in
6,101
pres pyeval_callobject(pmethpargs)py_decref(pmeth)py_decref(pargs)if (pres =nullerror("error calling klass method")if (!pyarg_parse(pres" "&cstr)error("can' convert klass method result")printf("% \ "cstr)py_decref(pres)/call method( , */convert to *these lines of code (not counting its makefileachieve the same results as the lines of interactive python we ran earlier--not exactly stellar result from developer productivity perspectiveneverthelessthe model it uses allows and +to leverage python in the same way that python can employ and +as 'll discuss in this book' conclusion in momentsuch combinations can often be more powerful than their individual parts other integration topics in this the term integration has largely meant mixing python with components written in or +(or other -compatible languagesin extending and embedding modes but from broader perspectiveintegration also includes any other technology that lets us mix python components into largerheterogeneous systems to wrap up this this last section briefly summarizes handful of commonly used integration technologies beyond the api tools we've explored jythonjava integration we first met jython in and it was discussed earlier in this in the context of extending reallythoughjython is broader integration platform jython compiles python code to java bytecode for execution on the jvm the resulting java-based system directly supports two kinds of integrationextendingjython uses java' reflection api to allow python programs to call out to java class libraries automatically the java reflection api provides java type information at runtime and serves the same purpose as the glue code we've generated to plug libraries into python in this part of the book in jythonhoweverthis runtime type information allows largely automated resolution of java calls in python scripts--no glue code has to be written or generated embeddingjython also provides java pythoninterpreter class api that allows java programs to run python code in namespacemuch like the api tools we've used to run python code strings from programs in additionbecause jython implements all python objects as instances of java pyobject classit is straightforward for the java layer that encloses embedded python code to process python objects python/ integration
6,102
much like the integration strategies we've seen in this part of the book by adding simpler scripting language to java applicationsjython serves many of the same roles as the integration tools we've studied on the downsidejython tends to lag behind cpython developmentsand its reliance on java class libraries and execution environments introduces java dependencies that may be factor in some python-oriented development scenarios neverthelessjython provides remarkably seamless integration model and serves as an ideal scripting language for java applications for more on jythoncheck it out online at ironpythonc#net integration also mentioned earlierironpython does for #net what jython does for java (and in fact shares common inventor)--it provides seamless integration between python code and software components written for the net frameworkas well as its mono implementation on linux like jythonironpython compiles python source code to the net system' bytecode format and runs programs on the system' runtime engine as resultintegration with external components is similarly seamless also like jythonthe net effect is to turn python into an easy-to-use scripting language for #net-based applications and general-purpose rapid development tool that complements cfor more details on ironpythonvisit com integration on windows com defines standard and language-neutral object model with which components written in variety of programming languages may integrate and communicate python' pywin windows extension package allows python programs to implement both server and client in the com interface model as suchit provides an automated way to integrate python programs with programs written in other com-aware languages such as visual basic python scripts can also use com calls to script microsoft applications such as word and excelbecause these systems register com object interfaces on the other handcom implies level of dispatch indirection overhead and is not as platform agnostic as other approaches listed here for more information on com support and other windows extensionssee the web and refer to 'reilly' python programming on win by mark hammond and andy robinson corba integration there is also much open source support for using python in the context of corba-based application corba stands for the common object request brokerit' language-neutral way to distribute systems among communicating componentswhich speak through an object model architecture as suchit represents another way to integrate python components into larger system python' corba support includes public domain systems such omniorb like comother integration topics
6,103
for more detailssearch the web other languages as we discussed at the end of our extending coverageyou'll also find direct support for mixing python with other languagesincluding fortranobjective-cand others many support both extending (calling out to the integrated languagesas well as embedding (handling calls from the integrated languagesee the prior discussion and the web for more details some observers might also include the emerging pyjamas system in this category--by compiling python code to javascript codeit allows python programs to access ajax and web browser-based apis in the context of the rich internet applications discussed earlier in this booksee and network-based integration protocols finallythere is also support in the python world for internet-based data transport protocolsincluding soapand xml-rpc by routing calls across networks such systems support distributed architecturesand give rise to the notion of web services xml-rpc is supported by standard library module in pythonbut search the web for more details on these protocols as you can seethere are many options in the integration domain perhaps the best parting advice can give you is simply that different tools are meant for different tasks extension modules and types are ideal at optimizing systems and integrating librariesbut frameworks offer other ways to integrate components--jython and ironpython for using java and netscom for reusing and publishing objects on windowsxmlrpc for distributed servicesand so on as alwaysthe best tools for your programs will almost certainly be the best tools for your programs python/ integration
6,104
the end like the first part of this bookthis last part is single this time short one to provide some parting context this discusses python' roles and scope it explores some of the broader ideas of python' common roleswith the added perspective afforded by the rest of the book much of this is philosophical in naturebut it underscores some of the main reasons for using tool like python note that there are no reference appendixes here for additional reference resourcesconsult the python standard manuals available online or commercially published reference bookssuch as 'reilly' python pocket reference and others you can find in the usual places on the web for additional python core language materialsee 'reilly' learning python among other thingsthe fourth edition of that book also explores more advanced api construction tools such as propertiesdescriptorsdecoratorsand metaclasseswhich we skipped here because they fall into the core language category that book also explores unicode text in more depth than we did heresince it' an inherent part of python and for help on other python-related topicssee the resources available at python' official websiteengine
6,105
conclusionpython and the development cycle foreword for the fourth edition wrote the following conclusion in for the first edition of this bookat time when python' integration role as front-end scripting language was viewed as more important than it often is today since thenpython has emerged as one of the top four or five most widely used programming languages in the world as it has grown in popularityits focus on code quality and readabilityand their related impact on developer productivityseems to have become the more dominant factor behind python' success in factmost python programmers today write pure python codewithout ever having to know or care about external libraries typicallya small handful of developers integrate external libraries for the majority to leverage in their python code while integration still matterspython is largely about quality and productivity to most people today (see "the python "secret handshake"on page for more on python contemporary philosophybecause of this shiftsome of this conclusion may have grown bit narrow in deferencei've removed all the "postscriptupdates that appeared here in prior editions this edition retains the conclusion itselfthoughpartly because of its historical valuepartly because it still reflects the ideals that propelled python into the limelight in the first placeand partly because of its continued relevance to python users who still integrate hybrid systems (wellthatplus the jokesat the end of the daymany of us have gotten off this proverbial island by nowthanks to the rise of tools such as python indeedover the last years python has realized most of its original aspirations laid out here the choice before us today seems to be between keeping the boat from growing too heavy or learning to swim well
6,106
wellthe meaning of pythonanyway in the preface of this booki promised that we' return to the issue of python' roles after seeing how it is used in practice so in closinghere are some subjective comments on the broader implications of the language most of this conclusion remains unchanged since the first edition of this book was penned in but so are the factors that pushed python into the development spotlight as mentioned in the preface sidebarpython' focus is on concepts such as qualityproductivityportabilityand integration hope that this book has demonstrated some of the benefits of that focus in action along the waywe've seen python applied to systems programminggui developmentinternet scriptingdatabase and text processingand more and we've witnessed firsthand the application of the language and its libraries to realistically scaled software development taskswhich go above and beyond what many classify as "scripting hope you've also had some funthattoois part of the python story in this conclusioni wish now to return to the forest after our long walk among the trees--to revisit python' roles in more concrete terms in particularpython' role as prototyping tool can profoundly affect the development cycle "something' wrong with the way we program computersthis has to be one of the most overused lines in the business stillgiven time to ponder the big picturemost of us would probably agree that we're not quite there yet over the last few decadesthe computer software industry has made significant progress on streamlining the development task (anyone remember dropping punch cards?but at the same timethe cost of developing potentially useful computer applications is often still high enough to make them impractical moreoversystems built using modern tools and paradigms are often delivered far behind schedule software engineering remains largely defiant of the sort of quantitative measurements employed in other engineering fields in the software worldit' not uncommon to take one' best time estimate for new project and multiply by factor of two or three to account for unforeseen overheads in the development task this situation is clearly unsatisfactory for software managersdevelopersand end users the "gilligan factorit has been suggestedtongue in cheekthat if there were patron saint of software engineersthe honor would fall on none other than gilliganthe character in the pervasively popular american television show of the sgilligan' island gilligan is the enigmaticsneaker-clad first matewidely held to be responsible for the shipwreck that stranded the now-residents of the island conclusionpython and the development cycle
6,107
only the most meager of modern technological comfortsgilligan and his cohorts must resort to scratching out living using the resources naturally available in episode after episodewe observe the professor developing exquisitely intricate tools for doing the business of life on their remote islandonly to be foiled in the implementation phase by the ever-bungling gilligan but clearly it was never poor gilligan' fault how could one possibly be expected to implement designs for such sophisticated applications as home appliances and telecommunications devicesgiven the rudimentary technologies available in such an environmenthe simply lacked the proper tools for all we knowgilligan may have had the capacity for engineering on the grandest level but you can' get there with bananas and coconuts and pathologicallytime after timegilligan wound up inadvertently sabotaging the best of the professor' plansmisusingabusingand eventually destroying his inventions if he could just pedal his makeshift stationary bicycle faster and faster (he was led to believe)all would be well but in the endinevitablythe coconuts were sent hurling into the airthe palm branches came crashing down around his headand poor gilligan was blamed once again for the failure of the technology dramatic though this image may besome observers would consider it striking metaphor for the software industry like gilliganwe software engineers are often asked to perform tasks with arguably inappropriate tools like gilliganour intentions are soundbut technology can hold us back and like poor gilliganwe inevitably must bear the brunt of management' wrath when our systems are delivered behind schedule you can' get there with bananas and coconuts doing the right thing of coursethe gilligan factor is an exaggerationadded for comic effect but few would argue that the bottleneck between ideas and working systems has disappeared completely even todaythe cost of developing software far exceeds the cost of computer hardware and when software is finally deliveredit often comes with failure rates that would be laughable in other engineering domains why must programming be so complexlet' consider the situation carefully by and largethe root of the complexity in developing software isn' related to the role it' supposed to perform--usually this is well-definedreal-world process ratherit stems from the mapping of real-world tasks onto computer-executable models and this mapping is performed in the context of programming languages and tools the path toward easing the software bottleneck must therefore lieat least partiallyin optimizing the act of programming itself by deploying the right tools given this realistic doing the right thing
6,108
overheads inherent in our current tools the static language build cycle using traditional static languagesthere is an unavoidable overhead in moving from coded programs to working systemscompile and link steps add built-in delay to the development process in some environmentsit' common to spend many hours each week just waiting for static language application' build cycle to finish given that modern development practice involves an iterative process of buildingtestingand rebuildingsuch delays can be expensive and demoralizing (if not physically painfulof coursethis varies from shop to shopand in some domains the demand for performance justifies build-cycle delays but 've worked in +environments where programmers joked about having to go to lunch whenever they recompiled their systems except they weren' really joking artificial complexities with many traditional programming toolsyou can easily lose focusthe very act of programming becomes so complex that the real-world goal of the program is obscured traditional languages divert valuable attention to syntactic issues and development of bookkeeping code obviouslycomplexity isn' an end in itselfit must be clearly warranted yet some of our current tools are so complex that the language itself makes the task harder and lengthens the development process one language does not fit all many traditional languages implicitly encourage homogeneoussingle-language systems by making integration complexthey impede the use of multiple-language tools as resultinstead of being able to select the right tool for the task at handdevelopers are often compelled to use the same language for every component of an application since no language is good at everythingthis constraint inevitably sacrifices both product functionality and programmer productivity until our machines are as clever at taking directions as we are (arguablynot the most rational of goals)the task of programming won' go away but for the time beingwe can make substantial progress by making the mechanics of that task easier this topic is what want to talk about now conclusionpython and the development cycle
6,109
if this book has achieved its goalsyou should by now have good understanding of why python has been called "next-generation scripting language compared with similar toolsit has some critical distinctions that we're finally in position to summarizetcl like tclpython can be used as an embedded extension language unlike tclpython is also full-featured programming language for manypython' data structure tools and support for programming-in-the-large make it useful in more domains tcl demonstrated the utility of integrating interpreted languages with modules python provides similar functionality plus powerfulobject-oriented languageit' not just command string processor perl like perlpython can be used for writing shell toolsmaking it easy to use for system services unlike perlpython has simplereadable syntax and remarkably coherent design for somethis makes python easier to use and better choice for programs that must be reused or maintained by others without questionperl is powerful system administration tool but once we move beyond processing text and filespython' features become attractive scheme/lisp like scheme (and lisp)python supports dynamic typingincremental developmentand metaprogrammingit exposes the interpreter' state and supports runtime program construction unlike lisppython has procedural syntax that is familiar to users of mainstream languages such as and pascal if extensions are to be coded by end usersthis can be major advantage smalltalk like smalltalkpython supports object-oriented programming (oopin the context of highly dynamic language unlike smalltalkpython doesn' extend the object system to include fundamental program control flow constructs users need not come to grips with the concept of if statements as message-receiving objects to use python--python is more conventional icon like iconpython supports variety of high-level datatypes and operations such as listsdictionariesand slicing in more recent timespython' notions of iteration and generators approach icon' backtracking in utility unlike iconpython is fundamentally simple programmers (and end usersdon' need to master esoteric concepts such as full-blown backtracking just to get started basic like modern structured basic dialectspython has an interpretive/interactive nature unlike most basicspython includes standard support for advanced programming features such as classesmodulesexceptionshigh-level datatypesand enter python
6,110
solutionwhich is not controlled by commercially vested company java like javapython is general-purpose languagesupports oopexceptionsand modular designand compiles to portable bytecode format unlike javapython' simple syntax and built-in datatypes make development much more rapid python programs are typically one-third to one-fifth the size of the equivalent java program / +like and ++python is general-purpose language and can be used for longterm strategic system development tasks unlike compiled languages in generalpython also works well in tactical modeas rapid development language python programs are smallersimplerand more flexible than those written in compiled languages for instancebecause python code does not constrain datatypes or sizesit both is more concise and can be applied in broader range of contexts all of these languages (and othershave merit and unique strengths of their own--in factpython borrowed most of its features from languages such as these it' not python' goal to replace every other languagedifferent tasks require different toolsand mixed-language development is one of python' main ideas but python' blend of advanced programming constructs and integration tools make it natural choice for the problem domains we've talked about in this bookand many more but what about that bottleneckback to our original questionhow can the act of writing software be made easierat some levelpython is really "just another computer language it' certainly true that python the language doesn' represent much that' radically new from theoretical point of view so why should we be excited about python when so many languages have been tried alreadywhat makes python of interestand what may be its larger contribution to the development worldis not its syntax or semanticsbut its worldviewpython' combination of tools makes rapid development realistic goal in nutshellpython fosters rapid development by providing features like thesefast build-cycle turnaround very high-levelobject-oriented language integration facilities to enable mixed-language development specificallypython attacks the software development bottleneck on four frontsdescribed in the following sections conclusionpython and the development cycle
6,111
python' development cycle is dramatically shorter than that of traditional tools in pythonthere are no compile or link steps--python programs simply import modules at runtime and use the objects they contain because of thispython programs run immediately after changes are made and in cases where dynamic module reloading can be usedit' even possible to change and reload parts of running program without stopping it at all figure - shows python' impact on the development cycle figure - development cycles because python is interpretedthere' rapid turnaround after program changes and because python' parser is embedded in python-based systemsit' easy to modify programs at runtime for examplewe saw how gui programs developed with python allow developers to change the code that handles button press while the gui remains activethe effect of the code change may be observed immediately when the button is pressed again there' no need to stop and rebuild more generallythe entire development process in python is an exercise in rapid prototyping python lends itself to experimental and interactive program developmentand it encourages developing systems incrementally by testing components in isolation and putting them together later in factwe've seen that we can switch from testing components (unit teststo testing whole systems (integration testsarbitrarilyas illustrated in figure - but what about that bottleneck
6,112
python is "executable pseudocodepython' very high-level nature means there' less for us to program and manage the lack of compile and link steps isn' really enough to address the development cycle bottleneck by itself for instancea or +interpreter might provide fast turnaround but would still be almost useless for rapid developmentthe language is too complex and low level but because python is also simple languagecoding is dramatically fastertoo for exampleits dynamic typingbuilt-in objectsand garbage collection eliminate much of the manual bookkeeping code required in lower-level languages such as and +since things such as type declarationsmemory managementand common data structure implementations are conspicuously absentpython programs are typically fraction of the size of their and +equivalents there' less to write and readand there are fewer interactions among language componentsand thus there is less opportunity for coding errors because most bookkeeping code is missingpython programs are easier to understand and more closely reflect the actual problem they're intended to address and python' high-level nature not only allows algorithms to be realized more quickly but also makes it easier to learn the language python is oop done right for oop to be usefulit must be easy to apply python makes oop flexible tool by delivering it in dynamic language more importantlyits class mechanism is simplified subset of ++'sthis simplification is what makes oop useful in the context of rapid-development tool for instancewhen we looked at data structure classes in this bookwe saw that python' dynamic typing let us apply single class to variety of object typeswe didn' need to write variants for each supported type in exchange for not constraining typespython code becomes flexible and agile in factpython' oop is so easy to use that there' really no reason not to apply it in most parts of an application python' class model has features powerful enough for conclusionpython and the development cycle
6,113
with the problem we're trying to solve python fosters hybrid applications as we've seen earlier in this bookpython' extending and embedding support makes it useful in mixed-language systems without good integration facilitieseven the best rapid-development language is "closed boxand is not generally useful in modern development environments but python' integration tools make it usable in hybridmulticomponent applications as one consequencesystems can simultaneously utilize the strengths of python for rapid development and of traditional languages such as for rapid execution while it' possible and common to use python as standalone toolit doesn' impose this mode insteadpython encourages an integrated approach to application development by supporting arbitrary mixtures of python and traditional languagespython fosters spectrum of development paradigmsranging from pure prototyping to pure efficiency figure - shows the abstract case figure - the development mode "slideras we move to the left extreme of the spectrumwe optimize speed of development moving to the right side optimizes speed of execution and somewhere in between is an optimum mix for any given project with pythonnot only can we pick the proper mix for our projectbut we can also later move the rad slider in the picture arbitrarily as our needs changegoing to the right projects can be started on the left end of the scale in python and gradually moved toward the rightmodule by moduleas needed to optimize performance for delivery going to the left similarlywe can move strategic parts of existing or +applications on the right end of the scale to pythonto support end-user programming and customization on the left end of the scale this flexibility of development modes is crucial in realistic environments python is optimized for speed of developmentbut that alone isn' always enough by themselvesbut what about that bottleneck
6,114
can do much more as shown in figure - for instanceapart from standalone useone of python' most common roles splits systems into frontend components that can benefit from python' ease of use and backend modules that require the efficiency of static languages such as cc++or fortran figure - hybrid designs whether we add python frontend interfaces to existing systems or design them in early onsuch division of labor can open up system to its users without exposing its internals when developing new systemswe also have the option of writing entirely in python at first and then optimizing as needed for delivery by moving performance-critical components to compiled languages and because python and modules look the same to clientsmigration to compiled extensions is transparent prototyping doesn' make sense in every scenario sometimes splitting system into python frontend and / +backend up front works best and prototyping doesn' help much when enhancing existing systems but where it can be appliedearly prototyping can be major asset by prototyping in python firstwe can show results more quickly perhaps more criticallyend users can be closely involved in the early stages of the processas sketched in figure - the result is systems that more closely reflect their original requirements on sinking the titanic in shortpython is really more than languageit implies development philosophy the concepts of prototypingrapid developmentand hybrid applications certainly aren' new but while the benefits of such development modes are widely recognizedthere has been lack of tools that make them practical without sacrificing programming power this is one of the main gaps that python' design fillspython provides simple conclusionpython and the development cycle
6,115
but powerful rapid development languagealong with the integration tools needed to apply it in realistic development environments this combination arguably makes python unique among similar tools for instancetcl is good integration tool but not full-blown languageperl is powerful system administration language but weak integration tool but python' marriage of powerful dynamic language and integration opens the door to fundamentally faster development modes with pythonit' no longer necessary to choose between fast development and fast execution by nowit should be clear that single programming language can' satisfy all our development goals our needs are sometimes contradictorythe goals of efficiency and flexibility will probably always clash given the high cost of making softwarethe choice between development and execution speed is crucial although machine cycles are cheaper than programmerswe can' yet ignore efficiency completely but with tool like pythonwe don' need to decide between the two goals at all just as carpenter wouldn' drive nail with chainsawsoftware engineers are now empowered to use the right tool for the task at handpython when speed of development matterscompiled languages when efficiency dominatesand combinations of the two when our goals are not absolute moreoverwe don' have to sacrifice code reuse or rewrite exhaustively for delivery when applying rapid development with python we can have our rapid development cake and eat it tooon sinking the titanic
6,116
because python is high-levelobject-oriented languageit encourages writing reusable software and well-designed systems deliverability because python is designed for use in mixed-language systemswe don' have to move to more efficient languages all at once in many scenariosa system' frontend and infrastructure may be written in python for ease of development and modificationbut the kernel is still written in or +for efficiency python has been called the tip of the iceberg in such systems--the part visible to end users of packageas captured in figure - figure - "sinking the titanicwith mixed-language systems such an architecture uses the best of both worldsit can be extended by adding more python code or by writing extension modulesdepending on performance requirements but this is just one of many mixed-language development scenariossystem interfaces packaging libraries as python extension modules makes them more accessible end-user customization delegating logic to embedded python code provides for onsite changes pure prototyping python prototypes can be moved to all at once or piecemeal legacy code migration moving existing code from to python makes it simpler and more flexible standalone use of courseusing python all by itself leverages its existing library of tools python' design lets us apply it in whatever way makes sense for each project conclusionpython and the development cycle
6,117
as we've seen in this bookpython is multifaceted tooluseful in wide variety of domains what can we say about python to sum up herein terms of some of its best attributesthe python language isgeneral purpose object-oriented interpreted very high level openly designed widely portable freely available refreshingly coherent python is useful for both standalone development and extension workand it is optimized to boost developer productivity on many fronts but the real meaning of python is really up to youthe reader since python is general-purpose toolwhat it "isdepends on how you choose to use it in the final analysis hope this book has taught you something about pythonboth the language and its roles beyond this textthere is really no substitute for doing some original python programming be sure to grab reference source or two to help you along the way the task of programming computers will probably always be challenging perhaps happilythere will continue to be need for intelligent software engineersskilled at translating real-world tasks into computer-executable format least for the foreseeable future after allif it were too easynone of us would get paid no language or tool can obviate the hard work of full-scale programming entirely but current development practice and tools make our tasks unnecessarily difficultmany of the obstacles faced by software developers are purely artificial we have come far in our quest to improve the speed of computersthe time has come to focus our attention on improving the speed of development in an era of constantly shrinking schedulesproductivity must be paramount pythonas mixed-paradigm toolhas the potential to foster development modes that simultaneously leverage the benefits of rapid development and of traditional languages while python won' solve all the problems of the software industryit offers hope for making programming simplerfasterand at least little more enjoyable it may not get us off that island altogetherbut it sure beats bananas and coconuts in the final analysis
6,118
(the following was posted to the rec humor funny usenet newsgroup by larry hastingsand it is reprinted here with the original author' permission this has been percolating in the back of my mind for while it' scene from the empire strikes backreinterpreted to serve valuable moral lesson for aspiring programmers exteriordagobah--day with yoda strapped to his backluke climbs up one of the many thick vines that grow in the swamp until he reaches the dagobah statistics lab panting heavilyhe continues his exercises--greppinginstalling new packageslogging in as rootand writing replacements for two-year-old shell scripts in python yodacodeyes programmer' strength flows from code maintainability but beware of perl terse syntax more than one way to do it default variables the dark side of code maintainability are they easily they flowquick to join you when code you write if once you start down the dark pathforever will it dominate your destinyconsume you it will lukeis perl better than pythonyodano no no quickereasiermore seductive lukebut how will know why python is better than perlyodayou will know when your code you try to read six months from now conclusionpython and the development cycle
6,119
symbols (backslash) (forward slash) (pipe character) (underscore) wildcard character after method drawbacks functionality - scheduling functions algebrarelational anchoring widgets - animation coordinate system and graphics and other effects simple techniques - third-party toolkits threads and time sleep loops - anonymous pipes basic functionality - bidirectional ipc and - defined output stream buffering - threads and wrapping descriptors in file objects apache web servers append list operator arguments global variables versus pass-by-name threads and - array object (multiprocessing) ascii encoding askyesno function associated variables - asyncore py module attachments propagating sending via pymailcgi sending via pymailgui - viewing via pymailgui augmenting methods backslash (\) backupsverifying base module basic language bdfl acronym beautifulsoup third-party extension beazleydave bell method biggui client demo program - binary files defined parsing with struct module - random access processing - unicode encoding and binary mode transfers binary trees built-in options defined implementing - binascii module we' like to hear your suggestions for improving our indexes send email to index@oreilly com
6,120
binding events - - binding tags functionality binding events - - reserved port servers tags binhex module bitmapimage widget class - booleanvar class boost python system bound methods callback handlers and defined pymailgui program support recoding with - browsers cookie support displaying cgi context in grail pymailcgi send mail script - testing with urllib request - buffering command pipes and line - output streams button widget class command option functionality - buttons adding - adding in pycalc - deferring calls fixed-size quit button randomly changing images - bytearray string type bytecode files cleaning up - precompiling strings to - bytes string type - - language api standard classes and - embedding interface - index extending interface - getenv function putenv function python comparison python support scanning files for patterns - strop extension module swig tool and - wrapping environment calls - +language - calcgui class calculators (see pycalc programcallable objects defined overview - registering - callback handlers adding user-defined additional protocols binding events bound method callable class object deferring calls - defined lambda - registering objects - reloading dynamically - callbacks adding - arguments versus globals passing data with lambdas - placing on queues - canvas widget class addtag_withtag method basic operations controlling image displays coordinate system create_ method create_polygon method delete method event support - find_closest method freeform graphic support functionality image thumbnails - itemconfig method move method object construction
6,121
object tags postscript method programming - scrolling canvases - tag_bind method tkraise method update method xscrollcommand option xview method yscrollcommand option yview method canvases basic operations - clearing coordinate system defined dragging out object shapes event support - image thumbnails - moving objects object construction object identifiers object tags scrolling - cat command cd command cenviron module cgi module escape function - fieldstorage class functionality pymailcgi program and cgi scripts (see also pymailcgi programserver-side scripting/processingadding common input devices - adding pictures - adding user interaction - building first web page - changing input layouts - checking inputs - converting strings debugging - defined escape conventions - examples - formatting reply text functionality - - functions and generating tables - hello world program - installing - laying out forms with tables - model extensions name conventions passing parameters in hidden form fields passing parameters in urls - permissions programming suggestions query strings - refactoring code - running - saving state information in - text decoding issues urllib module and - using cookies in web servers and - writing - checkbutton widget class command option functionality - variables and - child process defined exiting from spawning chmod command class instances persistence and pickling storing in shelves - class object callback handlers classes adding behavior adding inheritance adding persistence - alternative language and - changing for objects container - customizing widgets with - moving graphs to - programming considerations - recoding with - refactoring scripts with - index
6,122
sets and - stacks and - client-side scripting/processing accessing newsgroups - accessing websites - additional options client socket calls console-based email client - development options fetching email via pop - handling multiple clients - internet applications and mailtools utility package - parsing/composing mail content - processing internet email - protocol considerations pymailgui program and python support sending email via smtp - spawning clients in parallel - transferring directories with ftplib transferring directory trees - transferring files over the internet transferring files with ftplib - urllib module - client/server architecture defined transferring files - clipboard interface clipping widgets closing files - cloud computing code files code strings defined precompiling - running in dictionaries running simple - running with results/namespaces colorsselecting on the fly columns in filessumming - com (component object model) command-line arguments accessing parsing sys module and - index command-line pipes buffering and gui programs and - sockets and command-line tools - common dialogs - comparedirs function comparing directory trees - connection objects (ftpcwd method defined mkd method retrbinary method retrlines method storbinary method storlines method console window avoiding dos consoles shelve interface - console-based email client (see pymail console clientconstructorscustomizing container classes - context managers file closure and - file filters and threads and - converting strings cookies creating defined handling with urllib request receiving security considerations using in cgi scripts coordinate systemcanvas copying directory trees - corba integration considerations orb support persistence options counting source code lines cregister module csh shell language ctypes module binary data and functionality integration considerations shared memory and
6,123
accessing command lines and defined import paths and cxx system cygwin system extension module +extension class forking processes running code strings cython system dabo builder data structures binary trees - graph searching - implementing sets - implementing stacks - permuting sequences - reversing/sorting sequences - subclassing built-in types - databases (see also sql databasesadditional information creating with sqlite displaying with pprint module freely available interfaces server-side db keys method dbm files defined shelve constraints and standard operations unicode and usage considerations - dbm module dcom (distributed component object model) deadlocksoutput stream buffering and debugging cgi scripts - delete statement (sql) deleting remote trees - dialog module dialogs custom - flavors of generating on demand - printing results - pyedit text editor reusable quit button selecting colors on the fly standard/common - dialogtable module dictionaries building - of dictionaries - implementing graph searching lists of making moving sets to - nested structures record examples running code strings in summing with dictionary iterators dir command filename patterns functionality usage example dirdiff tool - directories displaying images in finding differences - name conventions reporting differences in - scanning transferring with ftplib - walking - - web-based interfaces and - directory paths backslashes and scanning - scripts and splitting/joining listing results directory tools handling unicode filenames - overview walking directory trees - walking one directory - directory trees cleaning up bytecode files - comparing - copying - editing files in - finding differences - index
6,124
pyedit text editor scanning - searching - transferring with ftplib - walking - disutils package django framework __doc__ attribute formatting display functionality doctest framework documentation sources modules recent release manuals xml parsing dom parsers dos consoleavoiding doublevar class downloading files (see transferring filesdrakefred jr durus system earley algorithm ebcdic encoding editing files in directory trees - editvisitor class eibti acronym elementtree package elementtree parsing email console-based client - deleting - fetching at interactive prompt fetching via pop - handling html content inbox synchronization errors internationalization and - loading mailtools utility package - parsing/composing mail content - processing over internet - reading with direct urls recipient options - replies and forwards - sending at interactive prompt sending attachments - sending by smtp - - index unicode encoding and viewing attachments - email addresses - email module package basic interfaces - functionality internationalized headers limitations overview message address headers - message composition issues - message objects - message text generation issues - parser decoding requirement - pymailcgi program and pymailgui program and text payload encodings - embedding integration mode basic techniques - embedding api - defined registering callback handler objects enclosing scope reference mode - encryptionpassword - end-of-line character (\ncgi scripts overview in text files - text widget and endian-ness entry widget class associated variables and - functionality - laying out input forms - programming widgets xscrollcommand option xview method yscrollcommand option yview method environment variables (see shell variableseval function api equivalent converting strings parsing support pycalc support evaluator class event handlers (see callback handlersevents
6,125
canvas widget support - mouse-related - routing triggering exception handlersfile closure and - exec function api equivalent converting strings parsing support pycalc support exit status forking processes and shell command codes - threads and - expat parser extend list operator extending integration mode additional tools - defined overview simple module simple +class - swig tool - py system fastcgi extension ffi (foreign function interface) field labels (lists) - fieldstorage class fifos (see named pipesfile descriptors defined wrapping in file objects file download system - file objects alternate open options built-in - close method defined ensuring closure - file object model input files - output files - read method readline method readlines method seek method wrapping descriptors in write method writelines method file scanners - file tools binary files - built-in file objects - file object model file scanners - os module support overview text files - file transfer protocol (see ftpfiles (see also formatted filesclosing - code files current working directory and editing in directory trees - joiningloading database tables - name conventions opening persistence options private - redirecting streams to - sockets looking like - splitting - - summing columns in - system scripting and transferring over the internet transferring to clients/servers - transferring with ftplib - unicode text in writing filevisitor class - filters file scanning and spam find module - find shell command flash method flex framework fli format flushes deadlocks and output stream buffering and - fnmatch module - index
6,126
foreign function interface (ffi) forking processes fork/exec combination - functionality - obtaining exit status obtaining shared state os exec call formats server considerations - spawned child program formatted files data format script - test data script utility scripts forms action option changing input layouts - html tags - input - input fields laying out with tables - method option mocking up inputs passing parameters in hidden fields reusable form mock-up utility - sharing objects between pages - fortran language forward slash (/) frame widget class adding multiple widgets attaching widgets to frames functionality gui considerations menus - frozen binaries ftp (file transfer protocolfunctionality get and put utilities - timeout errors ftp objects cwd method delete method mkd methods nlst method ftplib module adding user interface - functionality transferring directories - index transferring directory trees - transferring files - functions cgi scripts and refactoring scripts with - sets and - threads and gaming toolkits gcc command generator functions geometry managers grid - - packer - - getaddresses utility getfile module ftp-based server-side examples socket-based - getopt module getpass getpass method gil (global interpreter lockatomic operations api thread considerations functionality - multiprocessing and thread switch interval threads and gilligan factor glob module button images functionality glob function scanning directories searching directory trees global interpreter lock (see gilglobal variables arguments versus multiprocessing module and - google app engine grail browser graph searching defined implementing - moving graphs to classes - graphical user interface (see guigrep command -
6,127
combining with packer - file download system functionality input forms laying out larger tables - making expandable packer comparison - reasons for using resizing in grids spanning rows/columns gui (graphical user interface) (see also tkinter moduleadding buttons - adding callback handlers - adding callbacks - adding multiple widgets - adding to non-gui code - additional information attaching frames - basic functionality - building for pycalc coding techniques - for command-line tools - customizing customizing widgets with classes - development options - geometry managers hello world program independent windows - inputting user data making widgets oop considerations - programming suggestions - reloading callback handlers - reusable components - running programs - shelve interface - threads and - - toolkit suggestions guimaker tool biggui client demo program - classes supported functionality - self-test subclass protocols guimixin tool functionality mixin utility classes - pycalc program widget builder functions guistreams tool functionality - redirecting packing scripts hashing technique hello world program - help function hidden fields passing header text in - passing parameters in passing state information in hlist widget holmes expert system shell functionality rule strings html basic overview building web pages with cgi script escape conventions - escaping mail text/passwords - file permission constraints form tags - hidden input fields internet applications and parsing support - pymailgui text extraction table tags url conflicts and html entities module html parser module fetched data considerations functionality - screen scraping support htmlgen tool http accessing websites - cookie support - http client module http cookiejar module http cookies module http server module https (secure http) http_cookie environment variable hyperlinks - index
6,128
iana (internet assigned numbers authority) icon language idle interface functionality running gui programs text editor positioning issues ietf (internet engineering task force) images adding with cgi scripts - displaying - processing with pil - scrolling thumbnails - - in toolbars - imagetk module imaplib module __import__ function independent programs sockets and starting independent windows - indexes inheritance classes and simpleeditor class and input class input files - input forms grid basics laying out - input function input/output streams capturing stderr stream cgi scripts and io bytesio class io stringio class output stream buffering - pymailcgi program and redirecting print calls redirecting to files/programs - redirecting to python objects - redirecting to widgets - redirecting with os popen redirecting with subprocess - redirection utility - sockets looking like - standard streams index user interaction and - insert command (sql) inter-process communication (see ipcinteract function internationalization message headers - mail content support - internet assigned numbers authority (iana) internet engineering task force (ietf) internet service providers (isps) internet-related scripting development options - handling multiple clients - library modules and - protocols and - python file server - sockets and - - sockets like files/streams - intvar class io bytesio class io stringio class ipc (inter-process communicationanonymous pipes - bidirectional - fastcgi and multiprocessing module and named pipes - overview shared memory signals - sockets - ironpython development options integration considerations overview isps (internet service providers) iteratorsline - java language javafx platform joining filesjoneschristopher jython development options
6,129
overview kennedybill kill shell command kwparsing system label widget class functionality pack method labelframe widget class labels bg option customizing expand option fg option fill option font attribute height attribute pack option width attribute lalr parsers lambda callback handlers callback scope issues - deferring calls - functionality lamp acronym language analysis (see text processing and language analysislanguages common module languages reply module - launchmodes module lexical analysis (see text processing and language analysislibrary modules - line buffering - lisp language list command (ftp) list comprehensionssumming with list operators append extend functionality listbox widget class curselection method functionality insert method programming - runcommand method xscrollcommand option xview method yscrollcommand option yview method lists database lists of dictionaries field labels - in-place modifications - sample records stacks as loops threads and - time sleep - ls command filename patterns shell command limitations crypto third-party package mac environment language support programming user interfaces tkinter support machine names mail configuration module - mail reader tool - mail sender script - mailbox module mailfetcher class - mailparser class mailsender class - mailtool class mailtools utility package initialization file mailfetcher class - mailparser class mailsender class - mailtool class overview pymail client and - pymailcgi and pymailgui and selftest py module - mainloop function (tkinter) index
6,130
match objects (re module) media filesplaying - menu widget class add_cascade method functionality - menubutton widget class - menus automating - defined displaying in windows - frame-based - menubutton-based - pyedit text editor top-level - message headers email addresses - internationalized mailtools utility package passing text in hidden fields - message objects composing messages - functionality - get_content_charset method get_payload method multipart messages message passing interface (mpistandard message widget class messagebox module mfc (microsoft foundation classes) mimetypes module functionality - guess_extension method guess_type method playing media files - selecting transfer modes minimal urls mixin utility classes - mmap module model-view-controller (mvcstructure module documentation sources mod_python module monty python theme song more function chaining with pipes functionality mouse-related events - mpeg format index mpi (message passing interfacestandard multiplexing servers - multiprocessing (see parallel processingmultiprocessing module additional tools supported - constraints functionality - gil and implementation ipc support - launching guis as programs - processes and locks - socket server portability and - starting independent programs usage rules muscianochuck mvc (model-view-controllerstructure mysql-python interface name conventions cgi scripts files __name__ variable named pipes basic functionality - creating defined use cases namespaces creating running code strings with - natural language processing nested structures dictionaries pickling uploading local trees - network news transfer protocol (nntp) - network scripting development options - handling multiple clients - library modules and - making sockets look like files/streams protocols and - python file server - sockets and - -
6,131
accessing - handling messages nltk suite nntp (network news transfer protocol) - nntplib module - numeric tools numpy programming extension object references callback handlers as deferring calls - object relational mappers (see ormsobject request broker (orb) object typesstoring in shelves object-oriented databases (oodbs) object-oriented programming (see oopobjects callable - - changing classes converting to strings pickled - sharing between pages - shelve constraints offline processingpymailgui program onsignal handler function oodbs (object-oriented databases) oop (object-oriented programmingadding behavior adding inheritance adding persistence - alternative database options class considerations - gui considerations - programming considerations - refactoring code - open function buffering policy functionality modes supported open source software opening files optimization in-place list modifications - moving sets to dictionaries - tuple tree stacks - optionmenu widget class optparse module orb (object request broker) orms (object relational mappersdatabase options functionality - os module administrative tools chdir function chmod function close function dup function dup function environ mapping accessing environment variables accessing shell variables changing shell variables env object functionality execl function execle function execlp function - execlpe function execv function execve function execvp function execvpe function _exit function fdopen function file tools supported fork function functionality os execlp combination - redirecting streams forking tools functionality getcwd function getenv function getpid function kill function linesep character listdir function fetching list of remote files handling unicode filenames joining files printing unicode filenames storing local files walking directory trees walking one directory index
6,132
mkdir function mkfifo function open function - pathsep character pipe function file descriptors and functionality redirecting output popen function communicating with exit status functionality launching mail program redirecting streams shell listing command - standard streams and portability constants program exits putenv function read function remove function rename function sep character shell commands from scripts - spawnv function - spawnve function - startfile function stat function system function tools by functional area unlink function walk function find function and functionality handling unicode filenames scanning directory trees - write function os path module abspath function functionality isdir function isfile function join function samefile function split function tools supported - output class output files - index output stream buffering deadlocks and flushes - pexpect and program exits and pty module and pack class packer geometry manager combining with grid - defined expand and fill options grid comparison - layout system making expandable resizing widgets packing scroll bars widgets without saving - paging script example panedwindow widget class parallel processing defined forking processes - ipc support - multiprocessing module - portable framework program exits - socket server portability and - spawning clients - starting programs - system tools coverage threads - parameters passing in hidden fields passing in hidden form fields passing in urls - - - query parent process parsing binary data - command-line arguments custom language parsers adding parse tree interpreter expression grammar parse tree structure parser code -
6,133
pytree gui and - writing defined email content - html support - parser decoding requirement - recursive descent regular expression support rule strings - with splits and joins xml support - passwords encrypting - escaping in html - pymailcgi password page pattern matching (see regular expressionspattern objects (re module) performance pymailcgi program and pymailgui program and saving thumbnail files stacks and string object methods and threads and perl language permissions cgi scripts and html constraints persistence dbm files - object relational mappers - options available pickled objects - programming considerations - shelve files - sql databases - zodb system - peterstim pexpect package output stream buffering and overview photoimage widget class - pickle module background information constraints - functionality - per-record pickle files - pickler class pymailgui program and unpickler class pickled objects defined usage considerations - pil (python imaging libraryextension toolkit animation and basics overview creating image thumbnails - displaying other image types - functionality images in toolbars thumbnail support pipe character (|) pipe object (multiprocessing) pipes anonymous - command-line - implementing multiprocessing module and named - sockets and unbuffered modes playfile module plone website builder plotting points on circle - ply parsing system pmw (python mega widgetsextension toolkit functionality scrolling support polymorphism pop (post office protocolfetching email at interactive prompt mail configuration module - mail reader script - overview pymailcgi and - - - pymailgui and - poplib module functionality mail reader script pymail script and pymailcgi program and popmail script - port numbers defined protocol rules reserved - index
6,134
displaying databases regular expression parsing and sax parsing and scanning directory trees print function cgi scripts and functionality redirecting standard streams and printing dialog results - unicode filenames - process class (multiprocessing) process forking (see forking processesprogram execution automated program launchers cgi scripts cross-program communication gui programs - launching email programs launching methods - persistence options pycalc program pymail console client - - pymailgui server-side scripts - threads and program exits with child threads os module process exit status and shared state shell commands and - sys module thread exits and shared state - programming python adding behavior adding gui - adding inheritance adding persistence - adding web-based interfaces - alternative database options class considerations - coding for reusability - console interaction - hello world program inputting user data internet development options - oop considerations - index programming pointers rapid development features - refactoring code - representing records - socket programming - storing records persistently - programs (see also spawned programschaining with pipes independent redirecting streams to - protocols client/server considerations defined development options pickle module and port number rules standards overview structural considerations psf (python software foundation) psp (python server pages) pty module putfile module py extension py exe tool pyarg_parse api function py_buildvalue api function pycalc program adding buttons - building gui calcgui class as component - evaluator class extending and attaching functionality - running running code strings source code - pyclock program functionality plotting points on circle - running - source code - widget support py_compilestring api function pycrypto system pydemos launcher toolbar -
6,135
pydict_new api function pydict_setitemstring api function pydoc system pydraw paint program functionality running source code - widget support pyedit text editor changes in version configuration module font dialog summarized undoredomodified tests changes in version improvements for running code modal dialog state fix new grep dialog - quit checks summarized unicode text support - update for initial positioning embedding in pyview - examples and screenshots functionality implementing launching menus and toolbars multiple windows - pymailgui program and running program code source code launch files main implementation file - overview user configuration file unicode support pyenchant third-party package pyerrata website pyeval_callobject api function pyeval_evalcode api function pyeval_getbuiltins api function pyform example - pyfort system pygadgets launcher toolbar - pygame package pygtk package pyimport_getmoduledict api function pyimport_importmodule api function py_initialize api function pyinstaller tool pyjamas toolkit pymail console client functionality - updating - pymailcgi program background information configuring fourth edition enhancements - implementation overview - presentation overview processing fetched mail delete action - deletions/pop message numbers overview - reply and forward reading pop email escaping mail text/passwords mail selection list page - message view page - passing state information - pop password page security protocols root page - running examples - sending mail by smtp common look-and-feel error pages message composition page overview send mail script - third edition enhancements - utility modules common utilities module - configuration external components overview pop mail interface pop password encryption - index
6,136
alternative approaches - pymailgui versus web versus desktop - pymailgui program components altconfigs module - functionality html text module - implementation overview - listwindows module - mailconfig module - main module - messagecache module - popuputil module - pymailguihelp program - sharednames module textconfig module viewwindows module - wraplines module - deleting email - email recipient options - email replies and forwards - extracting plain text frame-based menus getting started - html content in email improvement suggestions - load server interface loading mail mail content internationalization - major changes - multiple windows - offline processing - overview - placing callbacks on queues - pop support - presentation strategy pymailcgi versus running sending email and attachments source code modules and size - status messages - synchronization - index threading model - unicode support policies - viewing email and attachments - pymailguihelp program - pymodule_getdict api function pyobjc toolkit pyobject_callobject api function pyobject_getattrstring api function pyobject_setattrstring api function pyparsing system pyphoto image program limitations overview running - source code - widget support pypi website pyqt package pyrex system pyrun_file api function pyrun_simplestring api function pyrun_string api function pyserial interface python interpreter program python language internet development option - language comparisons - name origin third-party packages python server pages (psp) python software foundation (psf) pythoncard builder pythoninterpreter class api pythonioencoding environment variable pythonpath environment variable defined pickled class constraints running code strings syntax errors and pythonunbuffered environment variable pytoe game widget functionality running source code - pytree program - -
6,137
frame-based menus functionality running - source code - widget support pyw extension pywin package development options overview pyxml sig queries automating - cgi script support - parameter considerations running with sqlite - query_string environment variable queue module arguments versus globals functionality program exit with child threads running the script threads and queue object (multiprocessing) - queues placing callbacks on - placing data on - quit button quit method quopri module radiobutton widget class associated variables command option functionality - variables and - random access files - random module range function re module compile function escape function findall function finditer function functionality match function search function sub function subn function records adding with sqlite building dictionaries - built-in dictionaries - formatted files - list-based - per-record pickle files - pickle files - shelves and - recursive descent parsing refactoring code alternative classes augmenting methods with cgi scripts - with classes - constructor customization display format with functions - register_handler function regression test scripts - regular expressions defined limitations parsing support pattern examples - pattern matching techniques - pattern syntax - re module - scanning header files - string operations versus - remote sites deleting remote trees - downloading directories - downloading remote trees remote servers uploading directories - repeater method replacevisitor class reporting directory differences - reserved port numbers - retr string (ftp) rfc rfc module rias (rich internet applications) index
6,138
route_event function rule stringsparsing/unparsing - running programs (see program executions sax parsers scale widget class command option from_ option functionality - get/set methods label option resolution option showvalue option tickinterval option to option variables and - scanner function scanning header files for patterns - directories directory trees entire machines - module search paths - scheme language scipy package screen scraping scripts (see also cgi scriptsclient-side scriptinginternet-related scriptingnetwork scriptingserver-side scriptingsystem programssystem scriptingautomating queries - command-line arguments and - command-line mode - current working directory and - custom paging script data format script - launching queue module example refactoring with classes - refactoring with functions - regression test - running shell commands from - shell variables and - sql utility - standard streams and - start command in index start-up pointers test data script unix platforms and utility scripts web tradeoffs - scrollbar widget class functionality packing scroll bars programming set method scrolledcanvas class - scrolledlist component class scrolledtext component class search pathscgi scripts search_all script searcher function searching directory trees - searchvisitor class - secure sockets layer (ssl) security password encryption and - pymailcgi program and web-based interfaces and - select module functionality multiplexing servers - sendmail program sequences permuting - reversing/sorting - serial port interfaces serialization server-side databases server-side scripting/processing (see also cgi scriptspymailcgi programdevelopment options forking servers - internet applications and multiplexing servers with select - overview protocol considerations python file server - root page examples running - server socket calls - templating languages threading servers - transferring files - sets
6,139
built-in options classes and - defined functions and - moving to dictionaries - operations supported shared memory mmap module multiprocessing module and - threads and shared state forking processes and threads and - shell commands communicating with defined exit status codes - find kill limitations os module support running subprocess module alternative - shell variables accessing changing defined environment settings fetching wrapping calls - shellgui tool adding gui frontends to command lines - application-specific tool set classes functionality generic shell-tools display - gui input dialogs - non-gui scripts - shelve files changing classes of objects constraints - defined standard operations storing built-in object types storing class instances - usage considerations shelve module console interface - dictionary-of-dictionaries format and functionality - gui interface - open method pickle support and pymailgui program and unique objects and usage considerations web-based interfaces - writeback argument shutil module additional information functionality signal handlers - signal module alarm function functionality - pause function signal function signals defined functionality - silverlight framework simpleeditor class clipboard support functionality inheritance support limitations sip system smalltalk language smtp (simple mail transfer protocoldate formatting standard mail sender script - overview pymailcgi program - sending email at interactive prompt smtplib module functionality pymail script and pymailcgi program and pymailgui program and smtpmail script - soap integration considerations persistence options pickled objects and web services support socket module functionality - index
6,140
socket objects bind method close method connect method defined listen method makefile method send method setblocking method sockets basic functionality - - client calls command pipes and defined development options forked processes and independent programs and looking like files and streams - machine identifiers output stream buffering and pipes and practical usage considerations programming support running programs locally running programs remotely - server calls - spawning clients in parallel - spawning gui as separate programs talking to reserved ports - transferring byte strings/objects use cases socketserver module sorted function source code linescounting spam spark toolkit spawned programs command-line pipes - defined sockets example - - spawned threads (see threadsspelling checkers spinbox widget class splitting files - - sql databases additional resources api tutorial with sqlite - index building record dictionaries - code consolidation - functionality - interface overview - loading database tables from files sql utility scripts - sqlalchemy system sqlite database system adding records getting started making databases/tables overview running queries - running updates sqlobject system ssl (secure sockets layer) ssl module stacks built-in options - customizing performance monitors defined defining stack class - defining stack module - evaluating expressions with - in-place list modifications - as lists timing improvements - tuple tree - stajanofrank standard dialogs - standard streams (see input/output streamsstart command state information combining techniques extensions to cgi model hidden form input fields http cookies - internet applications and passing with pymailcgi - process exit status saving in cgi scripts - sax parsers and server-side databases thread exits - url query parameters status codesexit -
6,141
stor string (ftp) str object type functionality string method calls - text widget and - usage considerations - string methods basics overview - endswith method find method format method isdigit method isupper method join method pattern matching versus - performance and replace method templating with replacements/formats rjust method rstrip method split method startswith method strip method summing columns in files - upper method string module ascii_uppercase constant background information preset variables string methods and template feature strings (see also code stringsregular expressionsconverting converting objects to formatting - functionality query - shelve constraints specifying positions text widget as unicode text in - stringvar class strop module struct module functionality parsing binary data - serial ports and unpack method subclassing attaching class components - attaching frames built-in types - +class customizing widgets with classes - extending class components multiprocessing module and - protocol considerations pycalc program and recursive uploads reusable gui components - subprocess module exit status functionality popen object redirecting streams - sumgrid class summer function - swig tool - - synchronization inbox error potential mailtools utility package pymailgui program and - _thread module and - threading module - threads and sys module argv parameter command-line arguments - current working directory documentation sources exception details exc_info function exit function functionality getdefaultencoding function getrefcount function loaded modules table module search path modules dictionary platform string platforms and versions program exits setcheckinterval function standard streams and - index
6,142
capturing stream cgi scripts and functionality output stream buffering pymailcgi program and sys stdin cgi scripts and end-of-file character end-of-line character functionality redirecting to python objects - user interaction and - sys stdout cgi scripts and functionality output stream buffering redirecting print calls redirecting to python objects - system programs additional examples automated program launchers comparing directory trees - copying directory trees counting source code lines generating redirection web pages - playing media files - printing unicode filenames - recoding copies with classes - regression test scripts - scanning directories scanning directory trees scanning entire machine - scanning module search path - searching directory trees - splitting and joining files - walking directories - system scripting additional references bytes string type custom paging scripts file operations and module documentation sources overview paging documentation strings program usage considerations python library manuals string methods - system modules index unicode encoding system tools (see also parallel processingdefined os module - sys module - system scripting - systems application domain tables creating with sqlite description considerations generating - laying out forms - loading from files - orm support table display script - table load script tags binding form - objects table text tcl language telnet service telnetlib module tempfile module templating server-side languages supporting with replacements and formats testparser module text files buffered output streams and end-of-line translations - unicode encoding and - - text payload encodings - text processing and language analysis advanced language tools - custom language parsers - pycalc program regular expressions - strategies for string method utilities - xml and html parsing - text widget class
6,143
functionality - get method index support mark_set method programming - pymailgui program and search method tag support tag_add method tag_bind method tag_delete method tag_remove method text-editing operations - unicode and - xscrollcommand option xview method yscrollcommand option yview method text-mode transfers this module thread class _thread module allocate_lock function basic usage - coding alternatives - functionality running multiple threads - start_new_thread function synchronizing access - waiting for spawned thread exits - ways to code threads threading module functionality - synchronizing access - thread exits in guis timer function ways to code threads threads advantages using animation and anonymous pipes and exit considerations - global interpreter lock and - guis and - - potential usage downsides pyedit text editor pymailgui program and queue module - servers and - shared state - spawned _thread module - threading module - time sleep loops thumbnails (see also pyphoto image programcreating - scrollable canvases and - time module functionality sleep call - timeit module timer objects tix extension toolkit functionality hlist widget tk gui library tk widget class coding example destroy method exporting methods - functionality iconbitmap method iconify method maxsize method menu option - protocol method quit method title method withdraw method tkinter module (see also specific widget classeswidgetsafter method coding alternatives - coding basics configuring window titles createfilehandler tool documentation extensions supported - functionality - geometry managers implementation structure programming structure underscore character widget classes supported tkintertreectrl third-party extension index
6,144
primitive types representation is the essence of programming -"the mythical man month, brooks program updates variables in memory according to its instructions variables come in types-- type is classification of data that spells out possible values for that type and the operations that can be performed on it type can be provided by the language or defined by the programmer in python everything is an object--this includes booleansintegerscharactersetc primitive types boot camp writing program to count the number of bits that are set to in an integer is good way to get up to speed with primitive types the following program tests bits one-at- -time starting with the least-significant bit it illustrates shifting and maskingit also shows how to avoid hard-coding the size of the integer word def count_bits ( )num_bits while xnum_bits + >> return num_bits since we perform ( computation per bitthe time complexity is ( )where is the number of bits needed to represent the integere bits are needed to represent which is ( ) in binary the techniques in solution on the facing pagewhich is concerned with counting the number of bits modulo the paritycan be used to improve the performance of the program given above know your primitive types python has number of build-in typesnumerics ( integer)sequences ( list)mappings ( dict)as well as classesinstances and exceptions all instances of these types are objects integers in python are unbounded--the maximum integer representable is function of the available memory the constant sys maxsize can be used to find the word-sizespecificallyit' the maximum value integer that can be stored in the worde ** on -bit machine bounds on floats are specified in sys float_info be very familiar with the bit-wise operators such as & , | >> - << ~ ^ negative numbers are treated as their ' complement value (there is no concept of an unsigned shift in pythonsince integers have infinite precision
6,145
understand how to use masks and create them in an machine independent way know fast ways to clear the lowermost set bit (and by extensionset the lowermost get its indexetc understand signedness and its implications to shifting consider using cache to accelerate operations by using it to brute-force small inputs be aware that commutativity and associativity can be used to perform operations in parallel and reorder operations table top tips for primitive types the key methods for numeric types are abs(- )math ceil( )math floor( )min( ,- )max( )pow( (alternately * )and math sqrt( know how to interconvert integers and stringse str( )int(' ')floats and stringse str( )float(' 'unlike integersfloats are not infinite precisionand it' convenient to refer to infinity as float('inf'and float('-inf'these values are comparable to integersand can be used to create psuedo max-int and pseudo min-int when comparing floating point values consider using math isclose()--it is robuste when comparing very large valuesand can handle both absolute and relative differences the key methods in random are random randrange( )random randint( , )random random()random shuffle( )and random choice( computing the parity of word the parity of binary word is if the number of in the word is oddotherwiseit is for examplethe parity of is and the parity of is parity checks are used to detect single bit errors in data storage and communication it is fairly straightforward to write code that computes the parity of single -bit word how would you compute the parity of very large number of -bit wordshintuse lookup tablebut don' use entriessolutionthe brute-force algorithm iteratively tests the value of each bit while tracking the number of seen so far since we only care if the number of is even or oddwe can store the number modulo def parity ( )result while xresult ^
6,146
return result the time complexity is ( )where is the word size we will now describe several algorithms for parity computation that are superior to the bruteforce algorithm the first improvement is based on erasing the lowest set bit in word in single operationthereby improving performance in the bestand average-cases specificallythe expression ~( )where is the bitwise-and operator and is the bitwise complement operator the variable is at exactly the lowest bit of that is all other bits in are for exampleif ( ) then ( ) ~( ( ) and ( ) ( ) ( ) this calculation is robust--it is correct for unsigned and two' -complement representations consequentlythis bit may be removed from by computing ywhere is the bitwise-xor function the time complexity is ( )where is the number of bits set to in def parity ( )result while xresult ^ & drops the lowest set bit of return result let be the number of bits set to in particular word (for examplefor then time complexity of the algorithm above is (kthe fact that ~( isolates the lowest bit that is in is important enough that you should memorize it howeverit is also fairly easy to derive firstsuppose is not it has has bit that is one subtracting one from changes the rightmost bit to zero and sets all the lower bits to one (if you add one nowyou get the original value backthe effect is to mask out the rightmost one therefore ~( has single bit set to onenamelythe rightmost in now suppose is subtracting one from underflowsresulting in word in which all bits are set to one againx ~( is similar derivation shows that &( replaces the lowest bit that is with for exampleif ( ) then ( ) so &( ( ) &( ) ( ) this fact can also be very useful we now consider qualitatively different approach the problem statement refers to computing the parity for very large number of words when you have to perform large number of parity computationsandmore generallyany kind of bit fiddling computationstwo keys to performance are processing multiple bits at time and caching results in an array-based lookup table first we demonstrate caching clearlywe cannot cache the parity of every -bit integer--we would need bits of storagewhich is of the order of ten trillion exabytes howeverwhen computing the parity of collection of bitsit does not matter how we group those bitsi the computation is associative thereforewe can compute the parity of -bit integer by grouping its bits into four nonoverlapping bit subwordscomputing the parity of each subwordsand then computing the parity of these four subresults we choose since is relatively small
6,147
evenly divides the code is simpler than if we werefor exampleto use bit subwords we illustrate the approach with lookup table for -bit words the cache is --these are the parities of ( )( )( )( )respectively to compute the parity of ( we would compute the parities of ( )( )( )( by table lookup we see these are respectivelyso the final result is the parity of which is to lookup the parity of the first two bits in ( )we right shift by to get ( )and use this as an index into the cache to lookup the parity of the next two bitsi ( )we right shift by to get ( in the two least-significant bit places the right shift does not remove the leading ( )--it results in ( we cannot index the cache with thisit leads to an out-of-bounds access to get the last two bits after the right shift by we bitwise-and ( with ( (this is the "maskused to extract the last bitsthe result is ( similar masking is needed for the two other -bit lookups def parity ( )mask_size bit_mask xffff return precomputed_parity [ >( mask_size )precomputed_parity [( >( mask_size )bit_mask precomputed_parity [( >mask_size bit_mask precomputed_parity [ bit_mask ]the time complexity is function of the size of the keys used to index the lookup table let be the width of the words for which we cache the resultsand the word size since there are / termsthe time complexity is ( / )assuming word-level operationssuch as shiftingtake ( time (this does not include the time for initialization of the lookup table we can improve on the (nworst-case time complexity of the previous algorithms by exploiting some simple properties of parity specificallythe xor of two bits is defined to be if both bits are or both bits are otherwise it is xor has the property of being associativei it does not matter how we group bitsas well as commutativei the order in which we perform the xors does not change the result the xor of group of bits is its parity we can exploit this fact to use the cpu' word-level xor instruction to process multiple bits at time for examplethe parity of hb equals the parity of the xor of hb and hb the xor of these two -bit values can be computed with single shift and single -bit xor instruction we repeat the same operation on - - - - -and -bit operands to get the final result note that the leading bits are not meaningfuland we have to explicitly extract the result from the least-significant bit we illustrate the approach with an -bit word the parity of ( is the same as the parity of ( xored with ( ) of ( this in turn is the same as the parity of ( xored with ( ) of ( the final result is the xor of ( with ( ) note that the first xor yields ( )and only the last bits are relevant going forward the second xor yields ( )and only the last bits are relevant the third xor yields ( the last bit is the resultand to extract it we have to bitwise-and with ( def parity ( ) ^ > ^ >
6,148
^ > ^ > ^ > return the time complexity is (log )where is the word size note that we can combine caching with word-level operationse by doing lookup in the xor-based approach once we get to bits the actual runtimes depend on the input datae the refinement of the brute-force algorithm is very fast on sparse inputs howeverfor random inputsthe refinement of the brute-force is roughly faster than the brute-force algorithm the table-based approach is four times faster stilland using associativity reduces run time by another factor of two variantwrite expressions that use bitwise operatorsequality checksand boolean operators to do the following in ( time right propagate the rightmost set bit in xe turns ( ) to ( ) compute modulo power of twoe returns for mod test if is power of evaluates to true for false for all other values
6,149
arrays the machine can alter the scanned symbol and its behavior is in part determined by that symbolbut the symbols on the tape elsewhere do not affect the behavior of the machine -"intelligent machinery, turing the simplest data structure is the arraywhich is contiguous block of memory it is usually used to represent sequences given an array aa[idenotes the ( )th object stored in the array retrieving and updating [itakes ( time insertion into full array can be handled by resizingi allocating new array with additional memory and copying over the entries from the original array this increases the worst-case time of insertionbut if the new array hasfor examplea constant factor larger than the original arraythe average time for insertion is constant since resizing is infrequent deleting an element from an array entails moving all successive elements one over to the left to fill the vacated space for exampleif the array is ithen deleting the element at index results in the array (we do not care about the last value the time complexity to delete the element at index from an array of length is ( ithe same is true for inserting new element (as opposed to updating an existing entryarray boot camp the following problem gives good insight into working with arraysyour input is an array of integersand you have to reorder its entries so that the even entries appear first this is easy if you use (nspacewhere is the length of the array howeveryou are required to solve it without allocating additional storage when working with arrays you should take advantage of the fact that you can operate efficiently on both ends for this problemwe can partition the array into three subarraysevenunclassifiedand oddappearing in that order initially even and odd are emptyand unclassified is the entire array we iterate through unclassifiedmoving its elements to the boundaries of the even and odd subarrays via swapsthereby expanding even and oddand shrinking unclassified def even_odd ( )next_even next_odd len( while next_even next_odd if anext_even = next_even + elseanext_even ]anext_odd anext_odd ]anext_even next_odd -
6,150
temporary variable for performing the swap we do constant amount of processing per entryso the time complexity is (narray problems often have simple brute-force solutions that use (nspacebut there are subtler solutions that use the array itself to reduce space complexity to ( filling an array from the front is slowso see if it' possible to write values from the back instead of deleting an entry (which requires moving all entries to its right)consider overwriting it when dealing with integers encoded by an array consider processing the digits from the back of the array alternatelyreverse the array so the least-significant digit is the first entry be comfortable with writing code that operates on subarrays it' incredibly easy to make off-by- errors when operating on arrays--reading past the last element of an array is common error which has catastrophic consequences don' worry about preserving the integrity of the array (sortednesskeeping equal entries togetheretc until it is time to return an array can serve as good data structure when you know the distribution of the elements in advance for examplea boolean array of length is good choice for representing subset of { (when using boolean array to represent subset of { }allocate an array of size to simplify indexing when operating on arraysuse parallel logic for rows and for columns sometimes it' easier to simulate the specificationthan to analytically solve for the result for examplerather than writing formula for the -th entry in the spiral order for an matrixjust compute the output from the beginning table top tips for arrays know your array libraries arrays in python are provided by the list type (the tuple type is very similar to the list typewith the constraint that it is immutable the key property of list is that it is dynamically-resizedi there' no bound as to how many values can be added to it in the same wayvalues can be deleted and inserted at arbitrary locations know the syntax for instantiating liste [ ][ [ list(range( )(list comprehensiondescribed lateris also powerful tool for instantiating arrays the basic operations are len( ) append( ) remove( )and insert( know how to instantiate arraye [[ ][ ][ ]
6,151
complexitywhere is the length of the array understand how copy worksi the difference between and list(aunderstand what deep copy isand how it differs from shallow copyi how copy copy(adiffers from copy deepcopy(akey methods for list include min( )max( )binary search for sorted lists (bisect bisect( )bisect bisect_left( )and bisect bisect_right( )) reverse((in-place)reversed( (returns an iterator) sort((in-place)sorted( (returns copy)del [ (deletes the -th element)and del [ : (removes the sliceslicing is very succinct way of manipulating arrays it can be viewed as generalization of indexingthe most general form of slice is [ : : ]with all of ijand being optional let [ here are some examples of slicinga[ : is [ ] [ :is [ ] [: is [ ] [:- is [ ] [- :is [ ] [- :- is [ ] [ : : is [ ] [ : :- is [ ]and [::- is [ (reverses listslicing can also be used to rotate lista[ : [:krotates by to the left it can also be used to create copyb [:does (shallowcopy of into python provides feature called list comprehension that is succinct way to create lists list comprehension consists of ( an input sequence( an iterator over the input sequence( logical condition over the iterator (this is optional)and ( an expression that yields the elements of the derived list for example[ ** for in range( )yields [ ]and [ ** for in range( if = yields [ , although list comprehensions can always be rewritten using map()filter()and lambdasthey are clearer to readin large part because they do not need lambdas list comprehension supports multiple levels of looping this can be used to create the product of setse if [ and [' '' ']then [(xyfor in for in bcreates [( ' ')( ' ')( ' ')( ' ')( ' ')( ' ')it can also be used to convert list to liste if [[' '' '' '][' '' '' ']] for row in for in row creates [' '' '' '' '' '' 'two levels of looping also allow for iterating over each entry in liste if [[ ][ ]then [[ ** for in rowfor row in myields [[ ][ ]as general ruleit is best to avoid more than two nested comprehensionsand use conventional nested for loops--the indentation makes it easier to read the program finallysets and dictionaries also support list comprehensionswith the same benefits the dutch national flag problem the quicksort algorithm for sorting arrays proceeds recursively--it selects an element (the "pivot")reorders the array to make all the elements less than or equal to the pivot appear firstfollowed by all the elements greater than the pivot the two subarrays are then sorted recursively implemented naivelyquicksort has large run times and deep function call stacks on arrays with many duplicates because the subarrays may differ greatly in size one solution is to reorder the array so that all elements less than the pivot appear firstfollowed by elements equal to the pivot
6,152
because the dutch national flag consists of three horizontal bandseach in different color as an exampleassuming that black precedes white and white precedes grayfigure (bis valid partitioning for figure (aif gray precedes black and black precedes whitefigure (cis valid partitioning for figure (ageneralizingsuppose iand the pivot index is then [ so is valid partitioning for the same arrayif the pivot index is then [ so the arrays as well as are valid partitionings (abefore partitioning (ba three-way partitioning re(canother three-way partitionsembling the dutch national flag ingthe russian national flag figure illustrating the dutch national flag problem write program that takes an array and an index into aand rearranges the elements such that all elements less than [ (the "pivot"appear firstfollowed by elements equal to the pivotfollowed by elements greater than the pivot hintthink about the partition step in quicksort solutionthe problem is trivial to solve with (nadditional spacewhere is the length of we form three listsnamelyelements less than the pivotelements equal to the pivotand elements greater than the pivot consequentlywe write these values into the time complexity is (nwe can avoid using (nadditional space at the cost of increased time complexity as follows in the first stagewe iterate through starting from index then index etc in each iterationwe seek an element smaller than the pivot--as soon as we find itwe move it to the subarray of smaller elements via an exchange this moves all the elements less than the pivot to the start of the array the second stage is similar to the first onethe difference being that we move elements greater than the pivot to the end of the array code illustrating this approach is shown below red white blue range ( def dutch_flag_partition pivot_index )pivot apivot_index first passgroup elements smaller than pivot for in range(len( ))look for smaller element for in range( len( ))if [jpivot [ ] [ja[ ] [ibreak second passgroup elements larger than pivot
6,153
if [ipivot break look for larger element stop when we reach an element less than pivot since first pass has moved them to the start of for in reversed (range( ))if [jpivot [ ] [ja[ ] [ibreak the additional space complexity is now ( )but the time complexity is ( ) if / and all elements before are greater than [ ]and all elements after are less than [iintuitivelythis approach has bad time complexity because in the first pass when searching for each additional element smaller than the pivot we start from the beginning howeverthere is no reason to start from so far back--we can begin from the last location we advanced to (similar comments hold for the second pass to improve time complexitywe make single pass and move all the elements less than the pivot to the beginning in the second pass we move the larger elements to the end it is easy to perform each pass in single iterationmoving out-of-place elements as soon as they are discovered red white blue range ( def dutch_flag_partition pivot_index )pivot apivot_index first passgroup elements smaller than pivot smaller for in range(len( ))if [ipivot [ ]asmaller asmaller ] [ismaller + second passgroup elements larger than pivot larger len( for in reversed range(len( )))if [ipivot break elif [ipivot [ ]alarger alarger ] [ilarger - the time complexity is (nand the space complexity is ( the algorithm we now present is similar to the one sketched above the main difference is that it performs classification into elements less thanequal toand greater than the pivot in single pass this reduces runtimeat the cost of trickier implementation we do this by maintaining four subarraysbottom (elements less than pivot)middle (elements equal to pivot)unclassifiedand top (elements greater than pivotinitiallyall elements are in unclassified we iterate through elements in unclassifiedand move elements into one of bottommiddleand top groups according to the relative order between the incoming unclassified element and the pivot as concrete examplesuppose the array is currently - - ??? iwhere the pivot is and denotes unclassified elements there are three possibilities for the first unclassified
6,154
[ is less than the pivote [ - we exchange it with the first the new array is - - - ?? [ is equal to the pivoti [ we do not need to move itwe just advance to the next unclassified elementi the array is - - ?? [ is greater than the pivote [ we exchange it with the last unclassified elementi the new array is - - ?? note how the number of unclassified elements reduces by one in each case red white blue range ( def dutch_flag_partition pivot_index )pivot apivot_index keep the following invariants during partitioning bottom group [smaller middle group asmaller equal unclassified group aequal larger top group alarger :smaller equal larger len(akeep iterating as long as there is an unclassified element while equal larger aequal is the incoming unclassified element if aequal pivot asmaller ]aequal aequal ]asmaller smaller equal smaller equal elif aequal =pivot equal + elseaequal pivot larger - aequal ]alarger alarger ]aequal each iteration decreases the size of unclassified by and the time spent within each iteration is ( )implying the time complexity is (nthe space complexity is clearly ( variantassuming that keys take one of three valuesreorder the array so that all objects with the same key appear together the order of the subarrays is not important for exampleboth figures (band (con page are valid answers for figure (aon page use ( additional space and (ntime variantgiven an array of objects with keys that takes one of four valuesreorder the array so that all objects that have the same key appear together use ( additional space and (ntime variantgiven an array of objects with boolean-valued keysreorder the array so that objects that have the key false appear first use ( additional space and (ntime variantgiven an array of objects with boolean-valued keysreorder the array so that objects that have the key false appear first the relative ordering of objects with key true should not change use ( additional space and (ntime
6,155
strings string pattern matching is an important problem that occurs in many areas of science and information processing in computingit occurs naturally as part of data processingtext editingterm rewritinglexical analysisand information retrieval -"algorithms for finding patterns in strings, aho strings are ubiquitous in programming today--scriptingweb developmentand bioinformatics all make extensive use of strings string can be viewed as special kind of arraynamely one made out of characters we treat strings separately from arrays because certain operations which are commonly applied to strings--for examplecomparisonjoiningsplittingsearching for substringsreplacing one string by anotherparsingetc --do not make sense for general arrays you should know how strings are represented in memoryand understand basic operations on strings such as comparisoncopyingjoiningsplittingmatchingetc advanced string processing algorithms often use hash tables (and dynamic programming (page in this we present problems on strings which can be solved using basic techniques strings boot camp palindromic string is one which reads the same when it is reversed the program below checks whether string is palindromic rather than creating new string for the reverse of the input stringit traverses the input string forwards and backwardsthereby saving space notice how it uniformly handles even and odd length strings def is_palindromic ( )note that [~ifor in [ len( is [-( return all( [ = [~ifor in range (len( / )the time complexity is (nand the space complexity is ( )where is the length of the string know your string libraries the key operators and functions on strings are [ ]len( ) ts[ : (and all the other variants of slicing for lists described on page ) in ts strip() startswith(prefix) endswith(suffix)'euclid,axiom ,parallel linessplit(',') ' '',join(('gauss''prince of mathematicians'' - ')) tolower()and 'name namerank rankformat(name='archimedes'rank= it' important to remember that strings are immutable--operations like [ :or +' imply creating new array of characters that is then assigned back to this implies that concatenating single character times to string in for loop has ( time complexity (some
6,156
solutionbut subtler solutions that use the string itself to reduce space complexity to ( understand the implications of string type which is immutablee the need to allocate new string when concatenating immutable strings know alternatives to immutable stringse list in python updating mutable string from the front is slowso see if it' possible to write values from the back table top tips for strings implementations of python use tricks under-the-hood to avoid having to do this allocationreducing the complexity to ( interconvert strings and integers string is sequence of characters string may encode an integere " encodes in this problemyou are to implement methods that take string representing an integer and return the corresponding integerand vice versa your code should handle negative integers you cannot use library functions like stoi in ++parseint in javaand int in python implement string/integer inter-conversion functions hintbuild the result one digit at time solutionlet' consider the integer to string problem first if the number to convert is single digiti it is between and the result is easy to computeit is the string consisting of the single character encoding that digit if the number has more than one digitit is natural to perform the conversion digit-by-digit the key insight is that for any positive integer xthe least significant digit in the decimal representation of is mod and the remaining digits are / this approach computes the digits in reverse ordere if we begin with we get and are left with to convert then we get and are left with to convert finallywe get and there are no digits to convert the natural algorithm would be to prepend digits to the partial result howeveradding digit to the beginning of string is expensivesince all remaining digit have to be moved more time efficient approach is to add each computed digit to the endand then reverse the computed sequence if is negativewe record thatnegate xand then add '-before reversing if is our code breaks out of the iteration without writing any digitsin which case we need to explicitly set to convert from string to an integer we recall the basic working of positional number system base- number encodes the number brute-force algorithm then is to begin with the rightmost digitand iteratively add di to cumulative sum the efficient way to compute + is to use the existing value and multiply that by more elegant solution is to begin from the leftmost digit and with each succeeding digitmultiply the partial result by and add that digit for exampleto convert " to an integerwe initial the partial result to in the first iterationr in the second iteration and in the third iteration which is the final result negative numbers are handled by recording the sign and negating the result
6,157
is_negative false if xis_negative -xtrue [while trues append (chr(ord(' ' ) // if = break adds the negative sign back if is_negative return ('-if is_negative else '''joinreversed ( )def string_to_int ( )return functools reduce lambda running_sum crunning_sum string digits index ( ) [ [ ='-':] (- if [ ='-else base conversion in the decimal number systemthe position of digit is used to signify the power of that digit is to be multiplied with for example" denotes the number the base number system generalizes the decimal number systemthe string "ak- ak- "where <ai bdenotes in base- the integer ak- bk- write program that performs base conversion the input is stringan integer and another integer the string represents an integer in base the output should be the string representing the integer in base assume < < use "ato represent "bfor and "ffor (for exampleif the string is " " is and is then the result should be " "since hintwhat base can you easily convert to and fromsolutiona brute-force approach might be to convert the input to unary representationand then group the as multiples of etc for example( ) ( ) to convert to base there are two groups of and with three remainingso the result is ( ) this approach is hard to implementand has terrible time and space complexity the insight to good algorithm is the fact that all languages have an integer typewhich supports arithmetical operations like multiplyadddividemodulusetc these operations make the conversion much easier specificallywe can convert string in base to integer type using sequence of multiply and adds then we convert that integer type to string in base using sequence of modulus and division operations for examplefor the string is " " and then the integer valueexpressed in decimalis the least significant digit of the result is mod and we continue with / the next digit is mod which we denote by 'awe continue with / since mod and / the final digit is and the overall result is " the design of the algorithm nicely illustrates the use of reduction
6,158
it is natural to implement it using recursion def convert_base num_as_string )def construct_from_base num_as_int base)return ('if num_as_int = else construct_from_base num_as_int /base basestring hexdigits num_as_int base upper ()is_negative num_as_string [ ='-num_as_int functools reduce lambda xcx string hexdigits index ( lower ())num_as_string is_negative :] return ('-if is_negative else ''(' if num_as_int = else construct_from_base num_as_int )the time complexity is ( ( logb ))where is the length of the reasoning is as follows firstwe perform multiply-and-adds to get from then we perform logb multiply and adds to get the result the value is upper-bounded by bn and logb (bn logb
6,159
linked lists the -expressions are formed according to the following recursive rules the atomic symbols etc are -expressions null expression is also admitted if is an -expression so is ( if and are -expressions so is ( -"recursive functions of symbolic expressions, mccarthy list implements an ordered collection of valueswhich may include repetitions sepcificallya singly linked list is data structure that contains sequence of nodes such that each node contains an object and reference to the next node in the list the first node is referred to as the head and the last node is referred to as the tailthe tail' next field is null the structure of singly linked list is given in figure there are many variants of linked listse in doubly linked listeach node has link to its predecessorsimilarlya sentinel node or self-loop can be used instead of null to mark the end of the list the structure of doubly linked list is given in figure list is similar to an array in that it contains objects in linear order the key differences are that inserting and deleting elements in list has time complexity ( on the other handobtaining the kth element in list is expensivehaving (ntime complexity lists are usually building blocks of more complex data structures howeveras we will see in this they can be the subject of tricky problems in their own right figure example of singly linked list the number in hex below node indicates the memory address of that node figure example of doubly linked list for all problems in this unless otherwise statedeach node has two entries-- data fieldand next fieldwhich points to the next node in the listwith the next field of the last node being null its prototype is as followsclass listnode def __init__ (self data = next_node =none)self data data self next next_node
6,160
there are two types of list-related problems--those where you have to implement your own listand those where you have to exploit the standard list library we will review both these aspects herestarting with implementationthen moving on to list libraries implementing basic list api--searchinsertdelete--for singly linked lists is an excellent way to become comfortable with lists search for keydef search_list (lkey)while and data !keyl next if key was not present in the list will have become null return insert new node after specified nodeinsert new_node after node def insert_after (node new_node )new_node next node next node next new_node delete nodedelete the node past this one assume node is not tail def delete_after (node)node next node next next insert and delete are local operations and have ( time complexity search requires traversing the entire liste if the key is at the last node or is absentso its time complexity is ( )where is the number of nodes list problems often have simple brute-force solution that uses (nspacebut subtler solution that uses the existing list nodes to reduce space complexity to ( very oftena problem on lists is conceptually simpleand is more about cleanly coding what' specifiedrather than designing an algorithm consider using dummy head (sometimes referred to as sentinelto avoid having to check for empty lists this simplifies codeand makes bugs less likely it' easy to forget to update next (and previous for double linked listfor the head and tail algorithms operating on singly linked lists often benefit from using two iteratorsone ahead of the otheror one advancing quicker than the other table top tips for linked lists know your linked list libraries we now review the standard linked list librarywith the reminder that many interview problems that are directly concerned with lists require you to write your own list class under the hoodthe python list type is typically implemented as dynamically resized arrayand the key methods on it are described on page this is concerned specifically with
6,161
list types some of the key methods on these lists include returning the head/tailadding an element at the head/tailreturning the value stored at the head/tailand deleting the headtailor arbitrary node in the list test for cyclicity although linked list is supposed to be sequence of nodes ending in nullit is possible to create cycle in linked list by making the next field of an element reference to one of the earlier nodes write program that takes the head of singly linked list and returns null if there does not exist cycleand the node at the start of the cycleif cycle is present (you do not know the length of the list in advance hintconsider using two iteratorsone fast and one slow solutionthis problem has several solutions if space is not an issuethe simplest approach is to explore nodes via the next field starting from the head and storing visited nodes in hash table-- cycle exists if and only if we visit node already in the hash table if no cycle existsthe search ends at the tail (often represented by having the next field set to nullthis solution requires (nspacewhere is the number of nodes in the list brute-force approach that does not use additional storage and does not modify the list is to traverse the list in two loops--the outer loop traverses the nodes one-by-oneand the inner loop starts from the headand traverses as many nodes as the outer loop has gone through so far if the node being visited by the outer loop is visited twicea loop has been detected (if the outer loop encounters the end of the listno cycle exists this approach has ( time complexity this idea can be made to work in linear time--use slow iterator and fast iterator to traverse the list in each iterationadvance the slow iterator by one and the fast iterator by two the list has cycle if and only if the two iterators meet the reasoning is as followsif the fast iterator jumps over the slow iteratorthe slow iterator will equal the fast iterator in the next step nowassuming that we have detected cycle using the above methodwe can find the start of the cycleby first calculating the cycle length once we know there is cycleand we have node on itit is trivial to compute the cycle length to find the first node on the cyclewe use two iteratorsone of which is ahead of the other we advance them in tandemand when they meetthat node must be the first node on the cycle the code to do this traversal is quite simpledef has_cycle (head)def cycle_len (end)start step end while truestep + start start next if start is endreturn step fast slow head while fast and fast next and fast next nextslow fast slow next fast next next if slow is fastfinds the start of the cycle
6,162
for in range cycle_len (slow))cycle_len_advanced_iter cycle_len_advanced_iter next it head both iterators advance in tandem while it is not cycle_len_advanced_iter it it next cycle_len_advanced_iter cycle_len_advanced_iter next return it iter is the start of cycle return none no cycle let be the number of nodes to the start of the cyclec the number of nodes on the cycleand the total number of nodes then the time complexity is (fo(co( )-- (ffor both pointers to reach the cycleand (cfor them to overlap once the slower one enters the cycle variantthe following program purports to compute the beginning of the cycle without determining the length of the cycleit has the benefit of being more succinct than the code listed above is the program correctdef has_cycle (head)fast slow head while fast and fast next and fast next nextslow fast slow next fast next next if slow is fastthere is cycle tries to find the start of the cycle slow head both pointers advance at the same time while slow is not fastslow fast slow next fast next return slow slow is the start of cycle return none no cycle
6,163
stacks and queues linear lists in which insertionsdeletionsand accesses to values occur almost always at the first or the last node are very frequently encounteredand we give them special names -"the art of computer programmingvolume , knuth stacks support last-infirst-out semantics for inserts and deleteswhereas queues are first-infirst-out stacks and queues are usually building blocks in solution to complex problem as we will soon seethey can also make for stand-alone problems stacks stack supports two basic operations--push and pop elements are added (pushedand removed (poppedin last-infirst-out orderas shown in figure if the stack is emptypop typically returns null or throws an exception when the stack is implemented using linked list these operations have ( time complexity if it is implemented using an arraythere is maximum number of entries it can have--push and pop are still ( if the array is dynamically resizedthe amortized time for both push and pop is ( stack can support additional operations such as peekwhich returns the top of the stack without popping it pop push (ainitial configuration (bpopping ( (cpushing on to (bfigure operations on stack stacks boot camp the last-infirst-out semantics of stack make it very useful for creating reverse iterators for sequences which are stored in way that would make it difficult or impossible to step back from given element this program uses stack to print the entries of singly-linked list in reverse order
6,164
nodes [while headnodes append (head datahead head next while nodes printnodes pop ()the time and space complexity are ( )where is the number of nodes in the list learn to recognize when the stack lifo property is applicable for exampleparsing typically benefits from stack consider augmenting the basic stack or queue data structure to support additional operationssuch as finding the maximum element table top tips for stacks know your stack libraries some of the problems require you to implement your own stack classfor othersuse the built-in list-type append(epushes an element onto the stack not much can go wrong with call to push [- will retrievebut does not removethe element at the top of the stack pop(will remove and return the element at the top of the stack len( = tests if the stack is empty when called on an empty list sboth [- and pop(raise an indexerror exception implement stack with max api design stack that includes max operationin addition to push and pop the max method should return the maximum value stored in the stack hintuse additional storage to track the maximum value solutionthe simplest way to implement max operation is to consider each element in the stacke by iterating through the underlying array for an array-based stack the time complexity is (nand the space complexity is ( )where is the number of elements currently in the stack the time complexity can be reduced to (log nusing auxiliary data structuresspecificallya heap or bstand hash table the space complexity increases to (nand the code is quite complex suppose we use single auxiliary variablemto record the element that is maximum in the stack updating on pushes is easym max(me)where is the element being pushed howeverupdating on pop is very time consuming if is the element being poppedwe have no way of knowing what the maximum remaining element isand are forced to consider all the remaining elements we can dramatically improve on the time complexity of popping by cachingin essencetrading time for space specificallyfor each entry in the stackwe cache the maximum stored at or below that entry now when we popwe evict the corresponding cached value
6,165
elementwithcachedmax collections namedtuple ('elementwithcachedmax '('element ''max ')def __init__ (self)self _element_with_cached_max [def empty (self)return len(self _element_with_cached_max = def max(self)if self empty ()raise indexerror ('max ()empty stack 'return self _element_with_cached_max - max def pop(self)if self empty ()raise indexerror ('pop ()empty stack 'return self _element_with_cached_max pop (element def push(self )self _element_with_cached_max append self elementwithcachedmax (xx if self empty (else max(xself max ()))each of the specified methods has time complexity ( the additional space complexity is ( )regardless of the stored keys we can improve on the best-case space needed by observing that if an element being pushed is smaller than the maximum element already in the stackthen can never be the maximumso we do not need to record it we cannot store the sequence of maximum values in separate stack because of the possibility of duplicates we resolve this by additionally recording the number of occurrences of each maximum value see figure on the following page for an example class stack class maxwithcount def __init__ (self max count )self max self count max count def __init__ (self)self _element [self _cached_max_with_count [def empty (self)return len(self _element = def max(self)if self empty ()raise indexerror ('max ()empty stack 'return self _cached_max_with_count - max
6,166
if self empty ()raise indexerror ('pop ()empty stack 'pop_element self _element pop (current_max self _cached_max_with_count - max if pop_element =current_max self _cached_max_with_count - count - if self _cached_max_with_count - count = self _cached_max_with_count pop (return pop_element def push(self )self _element append (xif len(self _cached_max_with_count = self _cached_max_with_count append (self maxwithcount ( )elsecurrent_max self _cached_max_with_count - max if =current_max self _cached_max_with_count - count + elif current_max self _cached_max_with_count append (self maxwithcount ( )the worst-case additional space complexity is ( )which occurs when each key pushed is greater than all keys in the primary stack howeverwhen the number of distinct keys is smallor the maximum changes infrequentlythe additional space complexity is lesso( in the best-case the time complexity for each specified method is still ( aux , aux , , , , , , , , , aux , aux aux aux aux , , , , , , , , , , , aux aux aux aux , aux , aux , , aux figure the primary and auxiliary stacks for the following operationspush push push push push push push poppoppoppoppush push both stacks are initially emptyand their progression is shown from left-to-rightthen top-to-bottom the top of the auxiliary stack holds the maximum element in the stackand the number of times that element occurs in the stack the auxiliary stack is denoted by aux
6,167
queue supports two basic operations--enqueue and dequeue (if the queue is emptydequeue typically returns null or throws an exception elements are added (enqueuedand removed (dequeuedin first-infirst-out order the most recently inserted element is referred to as the tail or back elementand the item that was inserted least recently is referred to as the head or front element queue can be implemented using linked listin which case these operations have ( time complexity the queue api often includes other operationse method that returns the item at the head of the queue without removing ita method that returns the item at the tail of the queue without removing itetc dequeue (ainitial configuration (bqueue (aafter dequeue enqueue (cqueue (bafter enqueuing figure examples of enqueuing and dequeuing dequealso sometimes called double-ended queueis doubly linked list in which all insertions and deletions are from one of the two ends of the listi at the head or the tail an insertion to the front is commonly called pushand an insertion to the back is commonly called an inject deletion from the front is commonly called popand deletion from the back is commonly called an eject (different languages and libraries may have different nomenclature queues boot camp in the following programwe implement the basic queue api--enqueue and dequeue--as well as max-methodwhich returns the maximum element stored in the queue the basic idea is to use compositionadd private field that references library queue objectand forward existing methods (enqueue and dequeue in this caseto that object class queue def __init__ (self)self _data [def enqueue (self )self _data append (xdef dequeue (self)return self _data pop ( def max(self)return max(self _data the time complexity of enqueue and dequeue are the same as that of the library queuenamelyo( the time complexity of finding the maximum is ( )where is the number of entries
6,168
when order needs to be preserved table top tips for queues know your queue libraries some of the problems require you to implement your own queue classfor othersuse the collections deque class append(epushes an element onto the queue not much can go wrong with call to push [ will retrievebut not removethe element at the front of the queue similarlyq[- will retrievebut not removethe element at the back of the queue popleft(will remove and return the element at the front of the queue dequeing or accessing the head/tail of an empty collection results in an indexerror exception being raised compute binary tree nodes in order of increasing depth binary trees are formally defined in in particulareach node in binary tree has depthwhich is its distance from the root given binary treereturn an array consisting of the keys at the same level keys should appear in the order of the corresponding nodesdepthsbreaking ties from left to right for exampleyou should return hh ih ih ih ih ih ii for the binary tree in figure on page hintfirst think about solving this problem with pair of queues solutiona brute force approach might be to write the nodes into an array while simultaneously computing their depth we can use preorder traversal to compute this array--by traversing node' left child first we can ensure that nodes at the same depth are sorted from left to right now we can sort this array using stable sorting algorithm with node depth being the sort key the time complexity is dominated by the time taken to sorti ( log )and the space complexity is ( )which is the space to store the node depths intuitivelysince nodes are already presented in somewhat ordered fashion in the treeit should be possible to avoid full-blow sortthereby reducing time complexity furthermoreby processing nodes in order of depthwe do not need to label every node with its depth in the followingwe use queue of nodes to store nodes at depth and queue of nodes at depth after all nodes at depth are processedwe are done with that queueand can start processing the queue with nodes at depth putting the depth nodes in new queue def binary_tree_depth_order (tree)result curr_depth_nodes []collections deque (tree ]while curr_depth_nodes next_depth_nodes this_level collections deque ([][while curr_depth_nodes curr curr_depth_nodes popleft (if currthis_level append (curr data
6,169
next_depth_nodes +[curr left curr right if this_level result append this_level curr_depth_nodes next_depth_nodes return result since each node is enqueued and dequeued exactly oncethe time complexity is (nthe space complexity is ( )where is the maximum number of nodes at any single depth variantwrite program which takes as input binary tree and returns the keys in top downalternating left-to-right and right-to-left orderstarting from left-to-right for exampleif the input is the tree in figure on the following pageyour program should return hh ih ih ih ih ih ii variantwrite program which takes as input binary tree and returns the keys in bottom upleft-to-right order for exampleif the input is the tree in figure on the next pageyour program should return hh ih ih ih ih ih ii variantwrite program which takes as input binary tree with integer keysand returns the average of the keys at each level for exampleif the input is the tree in figure on the following pageyour program should return
6,170
binary trees the method of solution involves the development of theory of finite automata operating on infinite trees -"decidability of second order theories and automata on trees, rabin formallya binary tree is either emptyor root node together with left binary tree and right binary tree the subtrees themselves are binary trees the left binary tree is sometimes referred to as the left subtree of the rootand the right binary tree is referred to as the right subtree of the root binary trees most commonly occur in the context of binary search treeswherein keys are stored in sorted fashion on page howeverthere are many other applications of binary treesat high levelbinary tree are appropriate when dealing with hierarchies figure gives graphical representation of binary tree node is the root nodes and are the left and right children of depth depth depth height depth depth depth figure example of binary tree the node depths range from to node has the highest depth ( of any node in the treeimplying the height of the tree is often the node stores additional data its prototype is listed as followsclass binarytreenode def __init__ (self data=none left=none right =none)self data data self left left self right right
6,171
' left subtreewe will say is the left child of pand is the parent of lthe notion of right child is similar if node is left or right child of pwe say it is child of note that with the exception of the rootevery node has unique parent usuallybut not universallythe node object definition includes parent field (which is null for the rootobserve that for any node there exists unique sequence of nodes from the root to that node with each node in the sequence being child of the previous node this sequence is sometimes referred to as the search path from the root to the node the parent-child relationship defines an ancestor-descendant relationship on nodes in binary tree specificallya node is an ancestor of if it lies on the search path from the root to if node is an ancestor of dwe say is descendant of that node our convention is that node is an ancestor and descendant of itself node that has no descendants except for itself is called leaf the depth of node is the number of nodes on the search path from the root to nnot including itself the height of binary tree is the maximum depth of any node in that tree level of tree is all nodes at the same depth see figure on the preceding page for an example of the depth and height concepts as concrete examples of these conceptsconsider the binary tree in figure on the facing page node is the parent of and node is descendant of the search path to is haijkli the depth of is node is the node of maximum depthand hence the height of the tree is the height of the subtree rooted at is the height of the subtree rooted at is nodes dehmnand are the leaves of the tree full binary tree is binary tree in which every node other than the leaves has two children perfect binary tree is full binary tree in which all leaves are at the same depthand in which every parent has two children complete binary tree is binary tree in which every levelexcept possibly the lastis completely filledand all nodes are as far left as possible (this terminology is not universale some authors use complete binary tree where we write perfect binary tree it is straightforward to prove using induction that the number of nonleaf nodes in full binary tree is one less than the number of leaves perfect binary tree of height contains exactly + nodesof which are leaves complete binary tree on nodes has height blog nc left-skewed tree is tree in which no node has right childa right-skewed tree is tree in which no node has left child in either casewe refer to the binary tree as being skewed key computation on binary tree is traversing all the nodes in the tree (traversing is also sometimes called walking here are some ways in which this visit can be done traverse the left subtreevisit the rootthen traverse the right subtree (an inorder traversalan inorder traversal of the binary tree in figure on the preceding page visits the nodes in the following orderhdcebfhgajlmkniopi visit the roottraverse the left subtreethen traverse the right subtree ( preorder traversala preorder traversal of the binary tree in figure on the facing page visits the nodes in the following orderhabcdefghijklmnopi traverse the left subtreetraverse the right subtreeand then visit the root ( postorder traversala postorder traversal of the binary tree in figure on the preceding page visits the nodes in the following orderhdechgfbmlnkjpoiai let be binary tree of nodeswith height implemented recursivelythese traversals have (ntime complexity and (hadditional space complexity (the space complexity is dictated by the maximum depth of the function call stack if each node has parent fieldthe traversals can be done with ( additional space complexity
6,172
common variants binary trees boot camp good way to get up to speed with binary trees is to implement the three basic traversals--inorderpreorderand postorder def tree_traversal (root)if rootpreorder processes the root before the traversals of left and right children print('preorder %droot datatree_traversal (root leftinorder processes the root after the traversal of left child and before the traversal of right child print('inorder %droot datatree_traversal (root right postorder processes the root after the traversals of left and right children print('postorder %droot datathe time complexity of each approach is ( )where is the number of nodes in the tree although no memory is explicitly allocatedthe function call stack reaches maximum depth of hthe height of the tree thereforethe space complexity is (hthe minimum value for is log (complete binary treeand the maximum value for is (skewed treerecursive algorithms are well-suited to problems on trees remember to include space implicitly allocated on the function call stack when doing space complexity analysis please read the introduction to if you need refresher on recursion some tree problems have simple brute-force solutions that use (nspace solutionbut subtler solutions that uses the existing tree nodes to reduce space complexity to ( consider leftand right-skewed trees when doing complexity analysis note that (hcomplexitywhere is the tree heighttranslates into (log ncomplexity for balanced treesbut (ncomplexity for skewed trees if each node has parent fielduse it to make your code simplerand to reduce time and space complexity it' easy to make the mistake of treating node that has single child as leaf table top tips for binary trees test if binary tree is height-balanced binary tree is said to be height-balanced if for each node in the treethe difference in the height of its left and right subtrees is at most one perfect binary tree is height-balancedas is complete binary tree height-balanced binary tree does not have to be perfect or complete--see figure on the next page for an example
6,173
figure height-balanced binary tree of height write program that takes as input the root of binary tree and checks whether the tree is heightbalanced hintthink of classic binary tree algorithm solutionhere is brute-force algorithm compute the height for the tree rooted at each node recursively the basic computation is to compute the height for each node starting from the leavesand proceeding upwards for each nodewe check if the difference in heights of the left and right children is greater than one we can store the heights in hash tableor in new field in the nodes this entails (nstorage and (ntimewhere is the number of nodes of the tree we can solve this problem using less storage by observing that we do not need to store the heights of all nodes at the same time once we are done with subtreeall we need is whether it is height-balancedand if sowhat its height is--we do not need any information about descendants of the subtree' root def is_balanced_binary_tree (tree)balancedstatuswithheight collections namedtuple 'balancedstatuswithheight '('balanced ''height ')first value of the return value indicates if tree is balanced and if balanced the second value of the return value is the height of tree def check_balanced (tree)if not treereturn balancedstatuswithheight (true - base case left_result check_balanced (tree leftif not left_result balanced left subtree is not balanced return balancedstatuswithheight (false right_result check_balanced (tree right if not right_result balanced right subtree is not balanced return balancedstatuswithheight (false is_balanced absleft_result height right_result height < height maxleft_result height right_result height return balancedstatuswithheight is_balanced height
6,174
the program implements postorder traversal with some calls possibly being eliminated because of early termination specificallyif any left subtree is not height-balanced we do not need to visit the corresponding right subtree the function call stack corresponds to sequence of calls from the root through the unique path to the current nodeand the stack height is therefore bounded by the height of the treeleading to an (hspace bound the time complexity is the same as that for postorder traversalnamely (nvariantwrite program that returns the size of the largest subtree that is complete variantdefine node in binary tree to be -balanced if the difference in the number of nodes in its left and right subtrees is no more than design an algorithm that takes as input binary tree and positive integer kand returns node in the binary tree such that the node is not -balancedbut all of its descendants are -balanced for examplewhen applied to the binary tree in figure on page if your algorithm should return node
6,175
heaps using -heaps we are able to obtain improved running times for several network optimization algorithms -"fibonacci heaps and their uses, fredman and tarjan heap is specialized binary tree specificallyit is complete binary tree as defined on page the keys must satisfy the heap property--the key at each node is at least as great as the keys stored at its children see figure (afor an example of max-heap max-heap can be implemented as an arraythe children of the node at index are at indices and the array representation for the max-heap in figure (ais max-heap supports (log ninsertionso( time lookup for the max elementand (log ndeletion of the max element the extract-max operation is defined to delete and return the maximum element see figure (bfor an example of deletion of the max element searching for arbitrary keys has (ntime complexity heap is sometimes referred to as priority queue because it behaves like queuewith one differenceeach element has "priorityassociated with itand deletion removes the element with the highest priority the min-heap is completely symmetric version of the data structure and supports ( time lookups for the minimum element (aa max-heap note that the root hold the maximum key (bafter the deletion of max of the heap in (adeletion is performed by replacing the root' key with the key at the last leaf and then recovering the heap property by repeatedly exchanging keys with children figure max-heap and deletion on that max-heap
6,176
suppose you were asked to write program which takes sequence of strings presented in "streamingfashionyou cannot back up to read an earlier value your program must compute the longest strings in the sequence all that is required is the longest strings--it is not required to order these strings as we process the inputwe want to track the longest strings seen so far out of these stringsthe string to be evicted when longer string is to be added is the shortest one min-heap (not max-heap!is the right data structure for this applicationsince it supports efficient find-minremove-minand insert in the program below we use heap with custom compare functionwherein strings are ordered by length def top_k (kstream )entries are compared by their lengths min_heap [len( )sfor in itertools islice (stream )heapq heapify min_heap for next_string in stream push next_string and pop the shortest string in min_heap heapq heappushpop (min_heap (lennext_string )next_string )return [ [ for in heapq nsmallest (kmin_heap )each string is processed in (log ktimewhich is the time to add and to remove the minimum element from the heap thereforeif there are strings in the inputthe time complexity to process all of them is ( log kwe could improve best-case time complexity by first comparing the new string' length with the length of the string at the top of the heap (getting this string takes ( timeand skipping the insert if the new string is too short to be in the set use heap when all you care about is the largest or smallest elementsand you do not need to support fast lookupdeleteor search operations for arbitrary elements heap is good choice when you need to compute the largest or smallest elements in collection for the formeruse min-heapfor the latteruse max-heap table top tips for heaps know your heap libraries heap functionality in python is provided by the heapq module the operations and functions we will use are heapq heapify( )which transforms the elements in into heap in-placeheapq nlargest(kl(heapq nsmallest(kl)returns the largest (smallestelements in lheapq heappush(he)which pushes new element on the heapheapq heappop( )which pops the smallest element from the heapheapq heappushpop(ha)which pushes on the heap and then pops and returns the smallest elementand [ ]which returns the smallest element on the heap without popping it it' very important to remember that heapq only provides min-heap functionality if you need to build max-heap on integers or floatsinsert their negative to get the effect of max-heap using heapq for objectsimplement __lt()__ appropriately
6,177
merge sorted files this problem is motivated by the following scenario you are given fileseach containing stock trade information for an & company each trade is encoded by line in the following format ,aapl, , the first number is the time of the trade expressed as the number of milliseconds since the start of the day' trading lines within each file are sorted in increasing order of time the remaining values are the stock symbolnumber of sharesand price you are to create single file containing all the trades from the filessorted in order of increasing trade times the individual files are of the order of - megabytesthe combined file will be of the order of five gigabytes in the abstractwe are trying to solve the following problem write program that takes as input set of sorted sequences and computes the union of these sequences as sorted sequence for exampleif the input is ih iand ithen the output is hintwhich part of each sequence is significant as the algorithm executessolutiona brute-force approach is to concatenate these sequences into single array and then sort it the time complexity is ( log )assuming there are elements in total the brute-force approach does not use the fact that the individual sequences are sorted we can take advantage of this fact by restricting our attention to the first remaining element in each sequence specificallywe repeatedly pick the smallest element amongst the first element of each of the remaining part of each of the sequences min-heap is ideal for maintaining collection of elements when we need to add arbitrary values and extract the smallest element for ease of expositionwe show how to merge sorted arraysrather than files as concrete examplesuppose there are three sorted arrays to be mergedh ih iand for simplicitywe show the min-heap as containing entries from these three arrays in practicewe need additional information for each entrynamely the array it is fromand its index in that array (in the file case we do not need to explicitly maintain an index for next unprocessed element in each sequence--the file / library tracks the first unread entry in the file the min-heap is initialized to the first entry of each arrayi it is { we extract the smallest entry and add it to the output which is then we add to the min-heap which is { now (we chose the entry corresponding to the third array arbitrarilyit would be perfectly acceptable to choose from the second array nextextract and add it to the output which is ithen add to the min-heap which is { nextextract and add it to the output which is ithen add to the min-heap which is { nextextract and add it to the output which is ithen add to the min-heap which is { nextextract and add it to the output which is iassuming is selected from the second arraywhich has no remaining elementsthe min-heap is { nextextract and add it to the output which is ithen add to the min-heap which is { nextextract and add it to the output which is ithe min-heap is { nextextract and add it to the output which is inowall elements are processed and the output stores the sorted elements def merge_sorted_arrays sorted_arrays )min_heap [builds list of iterators for each array in sorted_arrays sorted_arrays_iters [iter(xfor in sorted_arrays
6,178
for iit in enumerate sorted_arrays_iters )first_element next(it noneif first_element is not noneheapq heappush (min_heap first_element )result [while min_heap smallest_entry smallest_array_i heapq heappop min_heap smallest_array_iter sorted_arrays_iters smallest_array_i result append smallest_entry next_element nextsmallest_array_iter noneif next_element is not noneheapq heappush (min_heap next_element smallest_array_i )return result pythonic solution uses the heapq merge (method which takes multiple inputs def merge_sorted_arrays_pythonic sorted_arrays )return listheapq merge (sorted_arrays )let be the number of input sequences then there are no more than elements in the min-heap both extract-min and insert take (log ktime hencewe can do the merge in ( log ktime the space complexity is (kbeyond the space needed to write the final result in particularif the data comes from files and is written to fileinstead of arrayswe would need only (kadditional storage alternativelywe could recursively merge the filestwo at time using the merge step from merge sort we would go from to / then / etc files there would be log stagesand each has time complexity ( )so the time complexity is the same as that of the heap-based approachi ( log kthe space complexity of any reasonable implementation of merge sort would end up being ( )which is considerably worse than the heap based approach when
6,179
searching -"the anatomy of large-scale hypertextual web search engine, brin and page search algorithms can be classified in number of ways is the underlying collection static or dynamici inserts and deletes are interleaved with searchingis it worth spending the computational cost to preprocess the data so as to speed up subsequent queriesare there statistical properties of the data that can be exploitedshould we operate directly on the data or transform itin this our focus is on static data stored in sorted order in an array data structures appropriate for dynamic updates are the subject of and the first collection of problems in this are related to binary search the second collection pertains to general search
6,180
given an arbitrary collection of keysthe only way to determine if search key is present is by examining each element this has (ntime complexity fundamentallybinary search is natural elimination-based strategy for searching sorted array the idea is to eliminate half the keys from consideration by keeping the keys in sorted order if the search key is not equal to the middle element of the arrayone of the two sets of keys to the left and to the right of the middle element can be eliminated from further consideration questions based on binary search are ideal from the interviewers perspectiveit is basic technique that every reasonable candidate is supposed to know and it can be implemented in few lines of code on the other handbinary search is much trickier to implement correctly than it appears--you should implement it as well as write corner case tests to ensure you understand it properly many published implementations are incorrect in subtle and not-so-subtle ways-- study reported that it is correctly implemented in only five out of twenty textbooks jon bentleyin his book "programming pearlsreported that he assigned binary search in course for professional programmers and found that failed to code it correctly despite having ample time (bentley' students would have been gratified to know that his own published implementation of binary searchin column titled "writing correct programs"contained bug that remained undetected for over twenty years binary search can be written in many ways--recursiveiterativedifferent idioms for conditionalsetc here is an iterative implementation adapted from bentley' bookwhich includes his bug def bsearch (ta)lu len( while <um ( / if [mtl elif [ =treturn elseu return - the error is in the assignment ( in line which can potentially lead to overflow this overflow can be avoided by using ( the time complexity of binary search is given by (nt( / cwhere is constant this solves to (no(log )which is far superior to the (napproach needed when the keys are unsorted disadvantage of binary search is that it requires sorted array and sorting an array takes ( log ntime howeverif there are many searches to performthe time taken to sort is not an issue many variants of searching sorted array require little more thinking and create opportunities for missing corner cases searching boot camp when objects are comparablethey can be sorted and searched for using library search functions typicallythe language knows how to compare built-in typese integersstringslibrary classes
6,181
must explicitly implement comparisonand ensure this comparison has basic properties such as transitivity (if the comparison is implemented incorrectlyyou may find lookup into sorted collection failseven when the item is present suppose we are given as input an array of studentssorted by descending gpawith ties broken on name in the program belowwe show how to use the library binary search routine to perform fast searches in this array in particularwe pass binary search custom comparator which compares students on gpa (higher gpa comes first)with ties broken on name student collections namedtuple ('student '('name ''grade_point_average ')def comp_gpa student )return (student grade_point_average student namedef search_student (students target comp_gpa ) bisect bisect_left (comp_gpa (sfor in students ]comp_gpa target )return < lenstudents and students [ =target assuming the -th element in the sequence can be accessed in ( timethe time complexity of the program is (log nbinary search is an effective search tool it is applicable to more than just searching in sorted arrayse it can be used to search an interval of real numbers or integers if your solution uses sortingand the computation performed after sorting is faster than sortinge (nor (log )look for solutions that do not perform complete sort consider time/space tradeoffssuch as making multiple passes through the data table top tips for searching know your searching libraries the bisect module provides binary search functions for sorted list specificallyassuming is sorted list to find the first element that is not less than targeted valueuse bisect bisect_left( ,xthis call returns the index of the first entry that is greater than or equal to the targeted value if all elements in the list are less than xthe returned value is len(ato find the first element that is greater than targeted valueuse bisect bisect_right( ,xthis call returns the index of the first entry that is greater than the targeted value if all elements in the list are less than or equal to xthe returned value is len(ain an interviewif it is alloweduse the above functionsinstead of implementing your own binary search search sorted array for first occurrence of binary search commonly asks for the index of any element of sorted array that is equal to specified element the following problem has slight twist on this
6,182
- [ [ [ [ [ [ [ [ [ [ figure sorted array with repeated elements write method that takes sorted array and key and returns the index of the first occurrence of that key in the array for examplewhen applied to the array in figure your algorithm should return if the given key is if it is your algorithm should return hintwhat happens when every entry equals kdon' stop when you first see solutiona naive approach is to use binary search to find the index of any element equal to the keyk (if is not presentwe simply return - after finding such an elementwe traverse backwards from it to find the first occurrence of that element the binary search takes time (log )where is the number of entries in the array traversing backwards takes (ntime in the worst-case--consider the case where entries are equal to the fundamental idea of binary search is to maintain set of candidate solutions for the current problemif we see the element at index equals kalthough we do not know whether is the first element equal to kwe do know that no subsequent elements can be the first one therefore we remove all elements with index or more from the candidates let' apply the above logic to the given examplewith we start with all indices as candidatesi with [ the midpoint index contains therefore we can now update the candidate set to [ ]and record as an occurrence of the next midpoint is and this index contains - we update the candidate set to [ the value at the midpoint is so we update the candidate set to [ since the value at this midpoint is we update the first seen occurrence of to now the interval is [ ]which is emptyterminating the search--the result is def search_first_of_k (ak)left right result len( - [leftright is the candidate set while left <right mid (left right / if [midkright mid elif [mid=kresult mid right mid nothing to the right of mid can be solution elsea[midk left mid return result the complexity bound is still (log )--this is because each iteration reduces the size of the candidate set by half variantdesign an efficient algorithm that takes sorted array and keyand finds the index of the first occurrence of an element greater than that key for examplewhen applied to the array in figure your algorithm should return if the key is if it is - your algorithm should return
6,183
index local minimum if [iis less than or equal to its neighbors how would you efficiently find local minimumif one existsvariantwrite program which takes sorted array of integersand an integer kand returns the interval enclosing ki the pair of integers and such that is the first occurrence of in and is the last occurrence of in if does not appear in areturn [- - for example if and you should return [ variantwrite program which tests if is prefix of string in an array of sorted strings
6,184
hash tables the new methods are intended to reduce the amount of space required to contain the hash-coded information from that associated with conventional methods the reduction in space is accomplished by exploiting the possibility that small fraction of errors of commission may be tolerable in some applications -"space/time trade-offs in hash coding with allowable errors, bloom hash table is data structure used to store keysoptionallywith corresponding values insertsdeletes and lookups run in ( time on average the underlying idea is is to store keys in an array key is stored in the array locations ("slots"based on its "hash codethe hash code is an integer computed from the key by hash function if the hash function is chosen wellthe objects are distributed uniformly across the array locations if two keys map to the same locationa "collisionis said to occur the standard mechanism to deal with collisions is to maintain linked list of objects at each array location if the hash function does good job of spreading objects across the underlying array and take ( time to computeon averagelookupsinsertionsand deletions have ( /mtime complexitywhere is the number of objects and is the length of the array if the "loadn/ grows largerehashing can be applied to the hash table new array with larger number of locations is allocatedand the objects are moved to the new array rehashing is expensive ( ( mtimebut if it is done infrequently (for examplewhenever the number of entries doubles)its amortized cost is low hash table is qualitatively different from sorted array--keys do not have to appear in orderand randomization (specificallythe hash functionplays central role compared to binary search trees (discussed in )inserting and deleting in hash table is more efficient (assuming rehashing is infrequentone disadvantage of hash tables is the need for good hash function but this is rarely an issue in practice similarlyrehashing is not problem outside of realtime systems and even for such systemsa separate thread can do the rehashing hash function has one hard requirement--equal keys should have equal hash codes this may seem obviousbut is easy to get wronge by writing hash function that is based on address rather than contentsor by including profiling data softer requirement is that the hash function should "spreadkeysi the hash codes for subset of objects should be uniformly distributed across the underlying array in additiona hash function should be efficient to compute common mistake with hash tables is that key that' present in hash table will be updated the consequence is that lookup for that key will now faileven though it' still in the hash table if you have to update keyfirst remove itthen update itand finallyadd it back--this ensures it' moved the correct array location as ruleyou should avoid using mutable objects as keys
6,185
function should examine all the characters in the string it should give large range of valuesand should not let one character dominate ( if we simply cast characters to integers and multiplied thema single would result in hash code of we would also like rolling hash functionone in which if character is deleted from the front of the stringand another added to the endthe new hash code can be computed in ( time the following function has these propertiesdef string_hash (smodulus )mult return functools reduce lambda vc( mult ord( )modulus hash table is good data structure to represent dictionaryi set of strings in some applicationsa triewhich is tree data structure that is used to store dynamic set of stringshas computational advantages unlike bstnodes in the tree do not store key insteadthe node' position in the tree defines the key which it is associated with hash tables boot camp we introduce hash tables with two examples--one is an application that benefits from the algorithmic advantages of hash tablesand the other illustrates the design of class that can be used in hash table an application of hash tables anagrams are popular word play puzzleswhereby rearranging letters of one set of wordsyou get another set of words for example"eleven plus twois an anagram for "twelve plus onecrossword puzzle enthusiasts and scrabble players benefit from the ability to view all possible anagrams of given set of letters suppose you were asked to write program that takes as input set of words and returns groups of anagrams for those words each group must contain at least two words for exampleif the input is "debitcard""elvis""silent""badcredit""lives""freedom""listen""levis""moneythen there are three groups of anagrams( "debitcard""badcredit"( "elvis""lives""levis"( "silent""listen(note that "moneydoes not appear in any groupsince it has no anagrams in the set let' begin by considering the problem of testing whether one word is an anagram of another since anagrams do not depend on the ordering of characters in the stringswe can perform the test by sorting the characters in the string two words are anagrams if and only if they result in equal strings after sorting for examplesort("logarithmic"and sort("algorithmic"are both "acghiilmort"so "logarithmicand "algorithmicare anagrams we can form the described grouping of strings by iterating through all stringsand comparing each string with all other remaining strings if two strings are anagramswe do not consider the second string again this leads to an ( log malgorithmwhere is the number of strings and is the maximum string length looking more carefully at the above computationnote that the key idea is to map strings to representative given any stringits sorted version can be used as unique identifier for the anagram group it belongs to what we want is map from sorted string to the anagrams it corresponds to anytime you need to store set of stringsa hash table is an excellent choice our
6,186
sorted strings are keysand the values are arrays of the corresponding strings from the original input def find_anagrams dictionary )sorted_string_to_anagrams collections defaultdict (listfor in dictionary sorts the string uses it as key and then appends the original string as another value into hash table sorted_string_to_anagrams ['joinsorted ( ))append (sreturn group for group in sorted_string_to_anagrams values (if lengroup > the computation consists of calls to sort and insertions into the hash table sorting all the keys has time complexity (nm log mthe insertions add time complexity of (nm)yielding (nm log mtime complexity in total design of hashable class consider class that represents contacts for simplicityassume each contact is string suppose it is hard requirement that the individual contacts are to be stored in list and it' possible that the list contains duplicates two contacts should be equal if they contain the same set of stringsregardless of the ordering of the strings within the underlying list multiplicity is not importanti three repetitions of the same contact is the same as single instance of that contact in order to be able to store contacts in hash tablewe first need to explicitly define equalitywhich we can do by forming sets from the lists and comparing the sets in our contextthis implies that the hash function should depend on the strings presentbut not their orderingit should also consider only one copy if string appears in duplicate form it should be pointed out that the hash function and equals methods below are very inefficient in practiceit would be advisable to cache the underlying set and the hash coderemembering to void these values on updates class contactlist def __init__ (self names )''names is list of strings ''self names names def __hash__ (self)conceptually we want to hash the set of names since the set type is mutable it cannot be hashed therefore we use frozenset return hashfrozenset (self names )def __eq__ (self other )return set(self names =setother names def merge_contact_lists contacts )
6,187
contacts is list of contactlist ''return list(setcontacts )the time complexity of computing the hash is ( )where is the number of strings in the contact list hash codes are often cached for performancewith the caveat that the cache must be cleared if object fields that are referenced by the hash function are updated hash tables have the best theoretical and real-world performance for lookupinsert and delete each of these operations has ( time complexity the ( time complexity for insertion is for the average case-- single insert can take (nif the hash table has to be resized consider using hash code as signature to enhance performancee to filter out candidates consider using precomputed lookup table instead of boilerplate if-then code for mappingse from character to valueor character to character when defining your own type that will be put in hash tablebe sure you understand the relationship between logical equality and the fields the hash function must inspect specificallyanytime equality is implementedit is imperative that the correct hash function is also implementedotherwise when objects are placed in hash tableslogically equivalent objects may appear in different bucketsleading to lookups returning falseeven when the searched item is present sometimes you'll need multimapi map that contains multiple values for single keyor bi-directional map if the language' standard libraries do not provide the functionality you needlearn how to implement multimap using lists as valuesor find third party library that has multimap table top tips for hash tables know your hash table libraries there are multiple hash table-based data structures commonly used in python--setdictcollections defaultdictand collections counter the difference between set and the other three is that is set simply stores keyswhereas the others store key-value pairs all have the property that they do not allow for duplicate keysunlikefor examplelist in dictaccessing value associated with key that is not present leads to keyerror exception howevera collections defaultdict returns the default value of the type that was specified when the collection was instantiatede if collections defaultdict(list)then if not in then [kis [ collections counter is used for counting the number of occurrences of keyswith number of set-like operationsas illustrated below collections counter ( = = collections counter ( = = add two counters together [xd[ ]collections counter ({' ' ' ' } subtract keeping only positive counts )collections counter ({' ' } intersection min( [ ] [ ]collections counter ({' ' ' ' }
6,188
union max( [ ] [ ]collections counter ({' ' ' ' }the most important operations for set are add( ) remove( ) discard( ) in sas well as < (is subset of )and (elements in that are not in tthe basic operations on the three key-value collections are similar to those on set one difference is with iterators--iteration over key-value collection yields the keys to iterate over the key-value pairsiterate over items()to iterate over valuesuse values((the keys(method returns an iterator to the keys not every type is "hashable" can be added to set or used as key in dict in particularmutable containers are not hashable--this is to prevent client from modifying an object after adding it to the containersince the lookup will then fail to find it if the slot that the modified object hashes to is different note that the built-in hash(function can greatly simplify the implementation of hash function for user-defined classi implementing __hash(self)__ is an anonymous letter constructiblewrite program which takes text for an anonymous letter and text for magazine and determines if it is possible to write the anonymous letter using the magazine the anonymous letter can be written using the magazine if for each character in the anonymous letterthe number of times it appears in the anonymous letter is no more than the number of times it appears in the magazine hintcount the number of distinct characters appearing in the letter solutiona brute force approach is to count for each character in the character set the number of times it appears in the letter and in the magazine if any character occurs more often in the letter than the magazine we return falseotherwise we return true this approach is potentially slow because it iterates over all charactersincluding those that do not occur in the letter or magazine it also makes multiple passes over both the letter and the magazine--as many passes as there are characters in the character set better approach is to make single pass over the letterstoring the character counts for the letter in single hash table--keys are charactersand values are the number of times that character appears nextwe make pass over the magazine when processing character cif appears in the hash tablewe reduce its count by we remove it from the hash when its count goes to zero if the hash becomes emptywe return true if we reach the end of the letter and the hash is nonemptywe return false--each of the characters remaining in the hash occurs more times in the letter than the magazine def is_letter_constructible_from_magazine letter_text magazine_text )compute the frequencies for all chars in letter_text char_frequency_for_letter collections counter letter_text checks if characters in magazine_text can cover characters in char_frequency_for_letter for in magazine_text if in char_frequency_for_letter
6,189
if char_frequency_for_letter [ = del char_frequency_for_letter [cif not char_frequency_for_letter all characters for letter_text are matched return true empty char_frequency_for_letter means every char in letter_text can be covered by character in magazine_text return not char_frequency_for_letter pythonic solution that exploits collections counter note that the subtraction only keeps keys with positive counts def is_letter_constructible_from_magazine_pythonic letter_text magazine_text )return (not collections counter letter_text collections counter magazine_text )in the worst-casethe letter is not constructible or the last character of the magazine is essentially required thereforethe time complexity is ( nwhere and are the number of characters in the letter and magazinerespectively the space complexity is the size of the hash table constructed in the pass over the letteri ( )where is the number of distinct characters appearing in the letter if the characters are coded in asciiwe could do away with the hash table and use entry integer array awith [ibeing set to the number of times the character appears in the letter
6,190
sorting problem (meshingtwo monotone sequences stof lengths nmrespectivelyare stored in two systems of ( ) ( consecutive memory locationsrespectivelyss ( and tt ( it is desired to find monotone permutation of the sum [st]and place it at the locations rr ( )( -"planning and coding of problems for an electronic computing instrument, goldstine and von neumann sorting--rearranging collection of items into increasing or decreasing order--is common problem in computing sorting is used to preprocess the collection to make searching faster (as we saw with binary search through an array)as well as identify items that are similar ( students are sorted on test scoresnaive sorting algorithms run in ( time number of sorting algorithms run in ( log ntime--heapsortmerge sortand quicksort are examples each has its advantages and disadvantagesfor exampleheapsort is in-place but not stablemerge sort is stable but not in-placequicksort runs ( time in worst-case (an in-place sort is one which uses ( spacea stable sort is one where entries which are equal appear in their original order well-implemented quicksort is usually the best choice for sorting we briefly outline alternatives that are better in specific circumstances for short arrayse or fewer elementsinsertion sort is easier to code and faster than asymptotically superior sorting algorithms if every element is known to be at most places from its final locationa min-heap can be used to get an ( log kalgorithm if there are small number of distinct keyse integers in the range [ ]counting sortwhich records for each elementthe number of elements less than itworks well this count can be kept in an array (if the largest number is comparable in value to the size of the set being sortedor bstwhere the keys are the numbers and the values are their frequencies if there are many duplicate keys we can add the keys to bstwith linked lists for elements which have the same keythe sorted result can be derived from an in-order traversal of the bst most sorting algorithms are not stable merge sortcarefully implementedcan be made stable another solution is to add the index as an integer rank to the keys to break ties most sorting routines are based on compare function howeverit is also possible to use numerical attributes directlye in radix sort the heap data structure is discussed in detail in brieflya max-heap (min-heapstores keys drawn from an ordered set it supports (log ninserts and ( time lookup for the maximum (minimumelementthe maximum (minimumkey can be deleted in (log ntime heaps can be helpful in sorting problemsas illustrated by problem on page
6,191
it' important to know how to use effectively the sort functionality provided by your language' library let' say we are given student class that implements compare method that compares students by name then by defaultthe array sort library routine will sort by name to sort an array of students by gpawe have to explicitly speicify the compare function to the sort routine class student object )def __init__ (self name grade_point_average )self name name self grade_point_average grade_point_average def __lt__ (self other )return self name other name students student (' ' student (' ' student (' ' student (' ' sort according to __lt__ defined in student students remained unchanged students_sort_by_name sorted students sort students in place by grade_point_average students sort(keylambda student student grade_point_average the time complexity of any reasonable library sort is ( log nfor an array with entries most library sorting functions are based on quicksortwhich has ( space complexity sorting problems come in two flavors( use sorting to make subsequent steps in an algorithm simplerand ( design custom sorting routine for the formerit' fine to use library sort functionpossibly with custom comparator for the latteruse data structure like bstheapor array indexed by values certain problems become easier to understandas well as solvewhen the input is sorted the most natural reason to sort is if the inputs have natural orderingand sorting can be used as preprocessing step to speed up searching for specialized inpute very small range of valuesor small number of valuesit' possible to sort in (ntime rather than ( log ntime it' often the case that sorting can be implemented in less space than required by brute-force approach sometimes it is not obvious what to sort one should collection of intervals be sorted on starting points or endpoints(problem on page table top tips for sorting know your sorting libraries to sort list in-placeuse the sort(methodto sort an iterableuse the function sorted(the sort(method implements stable in-place sort for list objects it returns none-the calling list itself is updated it takes two argumentsboth optionalkey=noneand
6,192
and maps them to objects which are comparable--this function defines the sort order for exampleif =[ then sort(key=lambda xstr( )maps integers to stringsand is updated to [ ] the entries are sorted according to the lexicographical ordering of their string representation if reverse is set to truethe sort is in descending orderotherwise it is in ascending order the sorted function takes an iterable and return new list containing all items from the iterable in ascending order the original list is unchanged for exampleb sorted(akey=lambda xstr( )leaves unchangedand assigns to [ the optional arguments key and reverse work identically to sort compute the intersection of two sorted arrays natural implementation for search engine is to retrieve documents that match the set of words in query by maintaining an inverted index each page is assigned an integer identifierits documentid an inverted index is mapping that takes word and returns sorted array of page-ids which contain --the sort order could befor examplethe page rank in descending order when query contains multiple wordsthe search engine finds the sorted array for each word and then computes the intersection of these arrays--these are the pages containing all the words in the query the most computationally intensive step of doing this is finding the intersection of the sorted arrays write program which takes as input two sorted arraysand returns new array containing elements that are present in both of the input arrays the input arrays may have duplicate entriesbut the returned array should be free of duplicates for examplethe input is and iyour output should be hintsolve the problem if the input array lengths differ by orders of magnitude what if they are approximately equalsolutionthe brute-force algorithm is "loop join" traversing through all the elements of one array and comparing them to the elements of the other array let and be the lengths of the two input arrays def intersect_two_sorted_arrays (ab)return [ for ia in enumerate (aif ( = or ! [ ]and in bthe brute-force algorithm has (mntime complexity since both the arrays are sortedwe can make some optimizations firstwe can iterate through the first array and use binary search in array to test if the element is present in the second array def intersect_two_sorted_arrays (ab)def is_present ( ) bisect bisect_left (bkreturn len(band [ = return for ia in enumerate (aif ( = or ! [ ]and is_present (
6,193
further improve our run time by choosing the shorter array for the outer loop since if is much smaller than mthen log(mis much smaller than log(nthis is the best solution if one set is much smaller than the other howeverit is not the best when the array lengths are similar because we are not exploiting the fact that both arrays are sorted we can achieve linear runtime by simultaneously advancing through the two input arrays in increasing order at each iterationif the array elements differthe smaller one can be eliminated if they are equalwe add that value to the intersection and advance both (we handle duplicates by comparing the current element with the previous one for exampleif the arrays are and ithen we know by inspecting the first element of each that cannot belong to the intersectionso we advance to the second element of now we have common element which we add to the resultand then we advance in both arrays now we are at in both arraysbut we know has already been added to the result since the previous element in is also we advance in both again without adding to the intersection comparing to we can eliminate and advance to the fourth element in awhich is and equal to the element that ' iterator holdsso it is added to the result we then eliminate and since no elements remain in awe return def intersect_two_sorted_arrays (ab)ijintersection_a_b [while len(aand len( )if [ = [ ]if = or [ ! [ ]intersection_a_b append ( [ ]ij elif [ib[ ] + elsea[ib[jj + return intersection_a_b since we spend ( time per input array elementthe time complexity for the entire algorithm is ( render calendar consider the problem of designing an online calendaring application one component of the design is to render the calendari display it visually suppose each day consists of number of eventswhere an event is specified as start time and finish time individual events for day are to be rendered as nonoverlapping rectangular regions whose sides are parallel to the xand -axes let the -axis correspond to time if an event starts at time and ends at time ethe upper and lower sides of its corresponding rectangle must be at and erespectively figure on the next page represents set of events suppose the -coordinates for each day' events must lie between and ( pre-specified constant)and each event' rectangle must have the same "height(distance between the sides parallel to the -axisyour task is to compute the maximum height an event rectangle can have in essencethis is equivalent to the following problem write program that takes set of eventsand determines the maximum number of events that take place concurrently
6,194
figure set of nine events the earliest starting event begins at time the latest ending event ends at time the maximum number of concurrent events is { as well as others hintfocus on endpoints solutionthe number of events scheduled for given time changes only at times that are start or end times of an event this leads the following brute-force algorithm for each endpointcompute the number of events that contain it the maximum number of concurrent events is the maximum of this quantity over all endpoints if there are intervalsthe total number of endpoints is computing the number of events containing an endpoint takes (ntimesince checking whether an interval contains point takes ( time thereforethe overall time complexity is ( nxno( the inefficiency in the brute-force algorithm lies in the fact that it does not take advantage of localityi as we move from one endpoint to another intuitivelywe can improve the run time by sorting the set of all the endpoints in ascending order (if two endpoints have equal timesand one is start time and the other is an end timethe one corresponding to start time comes first if both are start or finish timeswe break ties arbitrarily now as we proceed through endpoints we can incrementally track the number of events taking place at that endpoint using counter for each endpoint that is the start of an intervalwe increment the counter by and for each endpoint that is the end of an intervalwe decrement the counter by the maximum value attained by the counter is maximum number of overlapping intervals for the example in figure the first seven endpoints are (start) (start) (start) (end) (end) (start) (endthe counter values are updated to event is tuple start_time end_time event collections namedtuple ('event '('start ''finish ')endpoint is tuple start_time or (end_time so that if times are equal start_time comes first endpoint collections namedtuple ('endpoint '('time ''is_start ')def find_max_simultaneous_events ( )builds an array of all endpoints (endpoint event start truefor event in aendpoint event finish false for event in ]sorts the endpoint array according to the time breaking ties by putting start times before end times sort(keylambda ( time not is_start )track the number of simultaneous events record the maximum number of simultaneous events max_num_simultaneous_events num_simultaneous_events for in
6,195
num_simultaneous_events + max_num_simultaneous_events maxnum_simultaneous_events max_num_simultaneous_events elsenum_simultaneous_events - return max_num_simultaneous_events sorting the endpoint array takes ( log ntimeiterating through the sorted array takes (ntimeyielding an ( log ntime complexity the space complexity is ( )which is the size of the endpoint array variantusers share an internet connection user uses bi bandwidth from time si to fi inclusive what is the peak bandwidth usage
6,196
binary search trees the number of trees which can be formed with given knots abg( ) - -" theorem on trees, cayley bsts are workhorse of data structures and can be used to solve almost every data structures problem reasonably efficiently they offer the ability to efficiently search for key as well as find the min and max elementslook for the successor or predecessor of search key (which itself need not be present in the bst)and enumerate the keys in range in sorted order bsts are similar to arrays in that the stored values (the "keys"are stored in sorted order howeverunlike with sorted arraykeys can be added to and deleted from bst efficiently specificallya bst is binary tree as defined in in which the nodes store keys that are comparablee integers or strings the keys stored at nodes have to respect the bst property--the key stored at node is greater than or equal to the keys stored at the nodes of its left subtree and less than or equal to the keys stored in the nodes of its right subtree figure on the next page shows bst whose keys are the first prime numbers key lookupinsertionand deletion take time proportional to the height of the treewhich can in worst-case be ( )if insertions and deletions are naively implemented howeverthere are implementations of insert and delete which guarantee that the tree has height (log nthese require storing and updating additional data at the tree nodes red-black trees are an example of height-balanced bsts and are widely used in data structure libraries common mistake with bsts is that an object that' present in bst is to updated the consequence is that lookup for that object returns falseeven though it' still in the bst as ruleavoid putting mutable objects in bst otherwisewhen mutable object that' in bst is to be updatedalways first remove it from the treethen update itthen add it back the bst prototype is as followsclass bstnode def __init__ (self data=none left=none right =none)self data self left self right data left right binary search trees boot camp searching is the single most fundamental application of bsts unlike hash tablea bst offers the ability to find the min and max elementsand find the next largest/next smallest element these operationsalong with lookupdelete and findtake time (log nfor library implementations of bsts both bsts and hash tables use (nspace--in practicea bst uses slightly more space
6,197
figure an example of bst the following program demonstrates how to check if given value is present in bst it is nice illustration of the power of recursion when operating on bsts def search_bst (tree key)return (tree if not tree or tree data =key else search_bst (tree left keyif key tree data else search_bst (tree right key)since the program descends tree with in each stepand spends ( time per levelthe time complexity is ( )where is the height of the tree with bst you can iterate through elements in sorted order in time ( (regardless of whether it is balancedsome problems need combination of bst and hashtable for exampleif you insert student objects into bst and entries are ordered by gpaand then student' gpa needs to be updated and all we have is the student' name and new gpawe cannot find the student by name without full traversal howeverwith an additional hash tablewe can directly go to the corresponding entry in the tree the bst property is global property-- binary tree may have the property that each node' key is greater than the key at its left child and smaller than the key at its right childbut it may not be bst table top tips for binary search trees know your binary search tree libraries some of the problems in this entail writing bst classfor othersyou can use bst library python does not come with built-in bst library the sortedcontainers module the best-in-class module for sorted sets and sorted dictionaries-it is performanthas clean api that is well documentedwith responsive community the underlying data structure is sorted list of sorted lists its asymptotic time complexity for inserts and deletes is on)since these operations entail insertion into list of length roughly nrather
6,198
for block data movements in the interests of pedagogywe have elected to use the bintrees module which implements sorted sets and sorted dictionaries using balanced bsts howeverany reasonable interviewer should accept sortedcontainers wherever we use bintrees belowwe describe the functionalities added by bintrees insert(einserts new element in the bst discard(eremoves in the bst if present min_item()/max_item(yield the smallest and largest key-value pair in the bst min_key()/max_key(yield the smallest and largest key in the bst pop_min()/pop_max(remove the return the smallest and largest key-value pair in the bst it' particularly important to note that these operations take (log )since they are backed by the underlying tree the following program illustrates the use of bintrees bintrees rbtree ([( 'alfa ')( 'bravo ')( 'charlie ')( 'delta ')( 'echo ')]print( [ ]'bravo print( min_item ( max_item ()( 'bravo ')( 'charlie '{ 'bravo ' 'delta ' 'alfa ' 'echo ' 'charlie ' 'golf ' insert ( 'golf 'print(tprint( min_key ( max_key () discard ( print( { 'bravo ' 'alfa ' 'echo ' 'charlie ' 'golf ' ( 'bravo ' pop_min (print( { 'alfa ' 'echo ' 'charlie ' 'golf ' ( 'golf ' pop_max (print( { 'alfa ' 'echo ' 'charlie ' test if binary tree satisfies the bst property write program that takes as input binary tree and checks if the tree satisfies the bst property hintis it correct to check for each node that its key is greater than or equal to the key at its left child and less than or equal to the key at its right childsolutiona direct approachbased on the definition of bstis to begin with the rootand compute the maximum key stored in the root' left subtreeand the minimum key in the root' right subtree we check that the key at the root is greater than or equal to the maximum from the left subtree and less than or equal to the minimum from the right subtree if both these checks passwe recursively check the root' left and right subtrees if either check failswe return false
6,199
key stored at its rootthe minimum key of the left subtreeand the minimum key of the right subtree the maximum key is computed similarly note that the minimum can be in either subtreesince general binary tree may not satisfy the bst property the problem with this approach is that it will repeatedly traverse subtrees in the worst-casewhen the tree is bst and each node' left child is emptythe complexity is ( )where is the number of nodes the complexity can be improved to (nby caching the largest and smallest keys at each nodethis requires (nadditional storage for the cache we now present two approaches which have (ntime complexity the first approach is to check constraints on the values for each subtree the initial constraint comes from the root every node in its left (rightsubtree must have key less than or equal (greater than or equalto the key at the root this idea generalizesif all nodes in tree must have keys in the range [lu]and the key at the root is (which itself must be between [lu]otherwise the requirement is violated at the root itself)then all keys in the left subtree must be in the range [lw]and all keys stored in the right subtree must be in the range [wuas concrete examplewhen applied to the bst in figure on page the initial range is [-for the recursive call on the subtree rooted at bthe constraint is [- ]the is the upper bound required by on its left subtree for the recursive call starting at the subtree rooted at fthe constraint is [ for the recursive call starting at the subtree rooted at kthe constraint is [ the binary tree in figure on page is identified as not being bst when the recursive call reaches --the constraint is [- ]but the key at is so the tree cannot satisfy the bst property def is_binary_tree_bst (tree low_range =float('-inf ')high_range float('inf '))if not treereturn true elif not low_range <tree data <high_range return false return is_binary_tree_bst (tree left low_range tree dataand is_binary_tree_bst (tree right tree data high_range )the time complexity is ( )and the additional space complexity is ( )where is the height of the tree alternativelywe can use the fact that an inorder traversal visits keys in sorted order furthermoreif an inorder traversal of binary tree visits keys in sorted orderthen that binary tree must be bst (this follows directly from the definition of bst and the definition of an inorder walk thus we can check the bst property by performing an inorder traversalrecording the key stored at the last visited node each time new node is visitedits key is compared with the key of the previously visited node if at any step in the walkthe key at the previously visited node is greater than the node currently being visitedwe have violation of the bst property all these approaches explore the left subtree first thereforeeven if the bst property does not hold at node which is close to the root ( the key stored at the right child is less than the key stored at the root)their time complexity is still (nwe can search for violations of the bst property in bfs mannerthereby reducing the time complexity when the property is violated at node whose depth is small specificallywe use queuewhere each queue entry contains nodeas well as an upper and lower bound on the keys stored at the subtree rooted at that node the queue is initialized to the