id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
8,700 | herewe read numberswith and occurring most frequentlyand with sample standard deviation of the statistics themselves are held in named tuple called statisticsstatistics collections namedtuple("statistics""mean mode median std_dev"the main(function also serves as an overview of the program' structuredef main()if len(sys... |
8,701 | collection data types we split every line on whitespaceand for each item we attempt to convert it to float if conversion succeeds--as it will for integers and for floating-point numbers in both decimal and exponential notations--we add the number to the numbers list and update the frequencies default dictionary (if we ... |
8,702 | if the number of modes is or greater than the maximum modes that are acceptablea mode of none is returnedotherwisea sorted list of the modes is returned def calculate_median(numbers)numbers sorted(numbersmiddle len(numbers/ median numbers[middleif len(numbers = median (median numbers[middle ] return median the median (... |
8,703 | collection data types count { : mean {mean:{fmt}median {median:{fmt}{ }std dev {std_dev:{fmt}}""formatcountmodelinefmt=real**statistics _asdict())str format( named tuple using str format(with mapping unpacking most of this function is concerned with formatting the modes list into the modeline string if there are no mod... |
8,704 | ( list pop())and the ability to have slices on the left-hand side of an assignmentto provide insertionreplacementand deletion of slices lists are ideal for holding sequences of itemsespecially if we need fast access by index position when we discussed the set and frozenset typeswe noted that they may contain only hasha... |
8,705 | collection data types in the next we will look more closely at python' control structuresand introduce one that we have not seen before we will also look in more depth at exception-handling and at some additional statementssuch as assertthat we have not yet covered in additionwe will cover the creation of custom functi... |
8,706 | control structures exception handling custom functions control structures and functions |||this first two sections cover python' control structureswith the first section dealing with branching and looping and the second section covering exception-handling most of the control structures and the basics of exception-handl... |
8,707 | the parentheses also make things clearer for human readers conditional expressions can be used to improve messages printed for users for examplewhen reporting the number of files processedinstead of printing " file( )"" file( )"and similarwe could use couple of conditional expressionsprint("{ file{ }format((count if co... |
8,708 | control structures and functions method does the same thingbut on failureinstead of raising an exception it returns an index of - there is no equivalent method for listsbut if we wanted function that did thiswe could create one using while loopdef list_find(lsttarget)index while index len(lst)if lst[index=targetbreak i... |
8,709 | if =targetbreak elseindex - return index as this code snippet impliesthe variables created in the for in loop' expression continue to exist after the loop has terminated like all local variablesthey cease to exist at the end of their enclosing scope exception handling ||python indicates errors and exceptional condition... |
8,710 | control structures and functions here is final version of the list_find(functionthis time using exceptionhandlingdef list_find(lsttarget)tryindex lst index(targetexcept valueerrorindex - return index herewe have effectively used the try except block to turn an exception into return valuethe same approach can also be us... |
8,711 | we set the file objectfhto none because it is possible that the open(call will failin which case nothing will be assigned to fh (so it will stay as none)and an exception will be raised if one of the exceptions we have specified occurs (ioerror or oserror)after printing the error message we return an empty list but note... |
8,712 | control structures and functions custom exceptions |custom exceptions are custom data types (classescreating classes is covered in but since it is easy to create simple custom exception typeswe will show the syntax hereclass exceptionname(baseexception)pass the base class should be exception or class that inherits from... |
8,713 | this cuts the code down to ten linesor including defining the exceptionand is much easier to read if the item is found we raise our custom exception and the except block' suite is executed--and the else block is skipped and if the item is not foundno exception is raised and so the else suite is executed at the end let'... |
8,714 | control structures and functions the function has various statesfor exampleafter reading an ampersand (&)it enters the parsing_entity stateand stores the characters between (but excludingthe ampersand and semicolon in the entity string set type the part of the code shown here handles the case when semicolon has been fo... |
8,715 | elif state =parsing_entityraise eoferror("missing ';at end of filenameat the end of parsing filewe need to check to see whether we have been left in the middle of an entity if we havewe raise an eoferrorthe built-in end-of-file exceptionbut give it our own message text we could just as easily have raised custom excepti... |
8,716 | control structures and functions online documentation although this book provides solid coverage of the python language and the built-in functions and most commonly used modules in the standard librarypython' online documentation provides considerable amount of reference documentationboth on the languageand particularl... |
8,717 | lambda functions are expressionsso they can be created at their point of usehoweverthey are much more limited than normal functions methods are functions that are associated with particular data type and can be used only in conjunction with the data type--they are introduced in when we cover object-oriented programming... |
8,718 | control structures and functions def letter_count(textletters=string ascii_letters)letters frozenset(letterscount for char in textif char in letterscount + return count we have specified default value for the letters parameter by using the parameter=default syntax this allows us to call letter_count(with just one argum... |
8,719 | control structures and functions using conditional expression we can save line of code for each parameter that has mutable default argument |names and docstrings using good names for function and its parameters goes long way toward making the purpose and use of the function clear to other programmers--and to ourselves ... |
8,720 | cause the function name says what is returnedand the parameter names clearly indicate what is expected none of the functions have any way of indicating what happens if the name isn' found--do they returnsay- or do they raise an exceptionsomehow such information needs to be documented for users of the function we can ad... |
8,721 | control structures and functions we can also use the sequence unpacking operator in function' parameter list this is useful when we want to create functions that can take variable number of positional arguments here is product(function that computes the product of the arguments it is givendef product(*args)result for a... |
8,722 | heron ( "sq inches" wrongraises typeerror in the third call we have attempted to pass fourth positional argumentbut the does not allow this and causes typeerror to be raised by making the the first parameter we can prevent any positional arguments from being usedand force callers to use keyword arguments here is such (... |
8,723 | control structures and functions can of course accept both variable number of positional arguments and variable number of keyword argumentsdef print_args(*args**kwargs)for iarg in enumerate(args)print("positional argument { { }format(iarg)for key in kwargsprint("keyword argument { { }format(keykwargs[key])this function... |
8,724 | control structures and functions "fr"but the global language variable used in the print_digits(function would remain unchanged as "enfor nontrivial programs it is best not to use global variables except as constantsin which case there is no need to use the global statement lambda functions |lambda functions are functio... |
8,725 | elements sort(key=lambda ( [ ] [ ])here the key function is lambda ( [ ] [ ]with being each -tuple element in the list the parentheses around the lambda expression are required when the expression is tuple and the lambda function is created as function' argument we could use slicing to achieve the same effectelements s... |
8,726 | control structures and functions preconditions and postconditions can be specified using assert statementswhich have the syntaxassert boolean_expressionoptional_expression if the boolean_expression evaluates to false an assertionerror exception is raised if the optional optional_expression is givenit is used as the arg... |
8,727 | no use to our users (and normally they wouldn' be)we can use the -oo option which in effect strips out both assert statements and docstringsnote that there is no environment variable for setting this option some developers take simpler approachthey produce copy of their program with all assert statements commented outa... |
8,728 | control structures and functions notice that for the second skeleton the name and year had as their defaults the values entered previouslyso they did not need to be retyped but no default for the filename is providedso when that was not given the skeleton was cancelled now that we have seen how the program is usedwe ar... |
8,729 | one custom exception is definedwe will see it in use when we look at couple of the program' functions the program' main(function is used to set up some initial informationand to provide loop on each iteration the user has the chance to enter some information for the html page they want generatedand after each one they ... |
8,730 | title xml sax saxutils escape(titledescription xml sax saxutils escape(descriptionkeywords ",join([xml sax saxutils escape(kfor in keywords]if keywords else "stylesheet (stylesheet_template format(stylesheetif stylesheet else ""html html_template format(**locals()to get the copyright text we call str format(on the copy... |
8,731 | control structures and functions def get_string(messagename="string"default=noneminimum_length= maximum_length= )message +"if default is none else [{ }]format(defaultwhile truetryline input(messageif not lineif default is not nonereturn default if minimum_length = return "elseraise valueerror("{ may not be emptyformatn... |
8,732 | tenance headaches--in the next we will see how to create custom modules with functionality that can be shared across any number of programs def get_integer(messagename="integer"default=noneminimum= maximum= allow_zero=true)this function is so similar in structure to the get_string(function that it would add nothing to ... |
8,733 | control structures and functions the also covered the use of the assert statement this statement is very useful for specifying the preconditions and postconditions that we expect to be true on every use of functionand can be real aid to robust programming and bug hunting in this we covered all the fundamentals of creat... |
8,734 | choose filenamemovies -no items are in the list -[ ]dd [ ]uit [ ] add itemlove actually love actually [ ]dd [ ]elete [ ]ave add itemabout boy about boy love actually [ ]dd [ ]elete [ ]ave add itemalien [ ]uit [ ] [ ]uit [ ] about boy alien love actually [ ]dd [ ]elete [ ]ave [ ]uit [ ] errorinvalid choice--enter one of... |
8,735 | control structures and functions when printing the list or the filenamesprint the item numbers using field width of if there are less than ten itemsof if there are less than itemsand of otherwise keep the items in case-insensitive alphabetical orderand keep track of whether the list is "dirty(has unsaved changesoffer t... |
8,736 | modules and packages overview of python' standard library |||modules whereas functions allow us to parcel up pieces of code so that they can be reused throughout programmodules provide means of collecting sets of functions (and as we will see in the next custom data typestogether so that they can be used by any number ... |
8,737 | modules is that programs are designed to be runwhereas modules are designed to be imported and used by programs not all modules have associated py files--for examplethe sys module is built into pythonand some modules are written in other languages (most commonlychowevermuch of python' library is written in pythonsofor ... |
8,738 | these syntaxes can cause name conflicts since they make the imported objects (variablesfunctionsdata typesor modulesdirectly accessible if we want to use the from import syntax to import lots of objectswe can use multiple lines either by escaping each newline except the lastor by enclosing the object names in parenthes... |
8,739 | at every subsequent import of the module python will detect that the module has already been imported and will do nothing when python needs module' byte-code compiled codeit generates it automatically--this differs fromsayjavawhere compiling to byte code must be done explicitly first python looks for file with the same... |
8,740 | modules png py tiff py xpm py as long as the graphics directory is subdirectory inside our program' directory or is in the python pathwe can import any of these modules and make use of them we must be careful to ensure that our top-level module name (graphicsis not the same as any top-level name in the standard library... |
8,741 | that is all that is requiredalthough we are free to put any other code we like in the __init__ py file now we can write different kind of import statementfrom graphics import image xpm load("sleepy xpm"the from package import syntax directly imports all the modules named in the __all__ list soafter this importnot only ... |
8,742 | modules import graphics vector svg as svg image svg load("snow svg"we can always use our own short name for moduleas we have done herealthough this does increase the risk of having name conflict all the imports we have used so far (and that we will use throughout the rest of the bookare absolute imports--this means tha... |
8,743 | triple quoted string that provides an overview of the module' contentsoften including some usage examples--this is the module' docstring here is the start of the textutil py file (but with the license comment lines omitted)#!/usr/bin/env python copyright ( - qtrac ltd all rights reserved ""this module provides few stri... |
8,744 | raw strings modules after the def line comes the function' docstringlaid out conventionally with single line descriptiona blank linefurther descriptionand then some examples written as though they were typed in interactively because the quoted strings are inside docstring we must either escape the backslashes inside th... |
8,745 | if counts[left= return false counts[left- return not any(counts values()the function builds two dictionaries the counts dictionary' keys are the opening characters ("(""[""{"and "<")and its values are integers the left_for_right dictionary' keys are the closing characters (")""]""}"and ">")and its values are the corres... |
8,746 | modules one really simple way to do this is to execute the examples in the docstrings and make sure that they produce the expected results this can be done by adding just three lines at the end of the module' py fileif __name__ ="__main__"import doctest doctest testmod(whenever module is imported python creates variabl... |
8,747 | we have used an ellipsis to indicate lot of lines that have been omitted if there are functions (or classes or methodsthat don' have teststhese are listed when the - option is used notice that the doctest module found the tests in the module' docstring as well as those in the functionsdocstrings examples in docstrings ... |
8,748 | modules by defaultthe chargrid render(function clears the screen before printing the gridbut this can be prevented by passing false as we have done here here is the grid that results from the preceding doctests%%%%%********************************************@@@@@@@@@@@@@@@pleasantville+++++++++@@@@@@@@@@@@@@%%%%######... |
8,749 | _char_assert_template ("char must be single character'{ }"is too long"_max_rows _max_columns _grid [_background_char here we define some private data for internal use by the module we use leading underscores so that if the module is imported using from chargrid import *none of these variables will be imported (an alter... |
8,750 | modules clear_screen(function since the function is not defined inside another function (or inside class as we will see in the next it is still global functionaccessible like any other function in the module after creating the function we explicitly set its docstringthis avoids us having to write the same docstring in ... |
8,751 | we will review just one of the drawing functions to give flavor of how the drawing is donesince our primary concern is with the implementation of the module here is the add_horizontal_line(functionsplit into two partsdef add_horizontal_line(rowcolumn column char="-")"""adds horizontal line to the grid using the given c... |
8,752 | modules almost at the end of the moduleafter all the functions have been definedthere is single call to resize()resize(_max_rows_max_columnsthis call initializes the grid to the default size ( and ensures that code that imports the module can safely make use of it immediately without this callevery time the module was ... |
8,753 | library (we will look at two such modules later onthe pyparsing and ply modules that are used to create parsers in in this section we present broad overview of what is on offertaking thematic approachbut excluding those packages and modules that are of very specialized interest and those which are platform-specific in ... |
8,754 | modules both lines of text are printed to sys stdouta file object that represents the "standard output stream"--this is normally the console and differs from sys stderrthe "error output streamonly in that the latter is unbuffered (python automatically creates and opens sys stdinsys stdoutand sys stderr at program start... |
8,755 | and has been in the library for long time the optparse module is newer and more powerful examplethe optparse module csv html py example back in we described the csv html py program in that exercises we proposed extending the program to accept the command-line arguments"maxwidthtaking an integer and "formattaking string... |
8,756 | mathematics and numbers modules |in addition to the built-in intfloatand complex numbersthe library provides the decimal decimal and fractions fraction numbers three numeric libraries are availablemath for the standard mathematical functionscmath for complex number mathematical functionsand random which provides many f... |
8,757 | examplethe calendardatetimeand time modules objects of type datetime datetime are usually created programmaticallywhereas objects that hold utc date/times are usually received from external sourcessuch as file timestamps here are some examplesimport calendardatetimetime moon_datetime_a datetime datetime( moon_time cale... |
8,758 | default dictionary named tuple ordered dictionary modules the collections package provides the collections defaultdict dictionary and the collections namedtuple collection data types that we have previously discussed in additionthis package provides the collections userlist and collections userdict typesalthough subcla... |
8,759 | import heapq heap [heapq heappush(heap( "rest")heapq heappush(heap( "work")heapq heappush(heap( "study")if we already have listwe can turn it into heap with heapq heapify(alist)this will do any necessary reordering in-place the smallest item can be removed from the heap using heapq heappop(heapfor in heapq merge([ ][ ]... |
8,760 | modules format for configuration files (similar to old-style windows ini filesis specified in rfc and the configparser module provides functions for reading and writing such files many applicationsfor exampleexcelcan read and write csv (comma separated valuedataor variants such as tab-delimited data the csv module can ... |
8,761 | bmquu pamvt +cwvv rcya uffmcki+bn tcwqcuzrdowbh zvcr+jzveaaaaaelftksuqmcc""we've omitted most of the lines as indicated by the ellipsis the data can be converted back to its original binary form like thisbinary base decode(left_align_pngthe binary data could be written to file using open(filename"wb"writebinarykeeping ... |
8,762 | modules def untar(archive)tar none trytar tarfile open(archivefor member in tar getmembers()if member name startswith(untrusted_prefixes)print("untrusted prefixignoring"member nameelif in member nameprint("suspect pathignoring"member nameelsetar extract(memberprint("unpacked"member nameexcept (tarfile tarerrorenvironme... |
8,763 | the filecmp module can be used to compare files with the filecmp cmp(function and to compare entire directories with the filecmp cmpfiles(function one very powerful and effective use of python programs is to orchestrate the running of other programs this can be done using the subprocess module which can start other pro... |
8,764 | modules if we need several pieces of information about file or directory we can use os stat()but if we need just one piecewe can use the relevant os path functionfor exampleos path exists()os path getsize()os path isfile()or os path isdir(the mimetypes module has the mimetypes guess_type(function that tries to guess th... |
8,765 | for sizefilename in sorted(data)names data[(sizefilename)if len(names print("{filename({sizebytesmay be duplicated "({ files):format(len(names)**locals())for name in namesprint("\ { }format(name)because the dictionary keys are (sizefilenametupleswe don' need to use key function to get the data sorted in size order if a... |
8,766 | modules client access to http requests is provided by the http client modulealthough the higher-level urllib package' modulesurllib parseurllib requesturllib responseurllib errorand urllib robotparserprovide easier and more convenient access to urls grabbing file from the internet is as simple asfh urllib request urlop... |
8,767 | ule we have already used the xml sax saxutils module for its xml sax saxutils escape(function (to xml-escape "&"""there is also an xml sax saxutils quoteattr(function that does the same thing but additionally escapes quotes (to make the text suitable for tag' attribute)and xml sax saxutils unescape(to do the opposite c... |
8,768 | modules we have cut out few lines and reduced the indentation that is present in the file the file is about in sizeso we have compressed it using gzip to more manageable unfortunatelythe element tree parser requires either filename or file object to readbut we cannot give it the compressed file since that will just app... |
8,769 | framework provided by the unittest module--this is python version of the java junit test framework the doctest module also provides some basic integration with the unittest module (testing is covered more fully in several third-party testing frameworks are also availablefor examplepy test from codespeak net/py/dist/tes... |
8,770 | summary modules ||the began by introducing the various syntaxes that can be used for importing packagesmodulesand objects inside modules we noted that many programmers only use the import importable syntax so as to avoid name clashesand that we must be careful not to give program or module the same name as top-level py... |
8,771 | for handling directories and files--and all of this is abstracted into platformindependent functions examples were shown for creating dictionary with filename keys and last modified timestamp valuesand for doing recursive search of directory to identify possible duplicate files based on their name and size large part o... |
8,772 | modules all platforms without having to remember the differences between dir and ls create program that supports the following interfaceusagels py [options[path [path pathn]]the paths are optionalif not given is used options- --help show this help message and exit - --hidden show hidden files [defaultoff- --modified sh... |
8,773 | the object-oriented approach custom classes custom collection classes object-oriented programming |||in all the previous we used objects extensivelybut our style of programming has been strictly procedural python is multiparadigm language--it allows us to program in proceduralobject-orientedand functional styleor in an... |
8,774 | object-oriented programming the object-oriented approach ||in this section we will look at some of the problems of purely procedural approach by considering situation where we need to represent circlespotentially lots of them the minimum data required to represent circle is its (xyposition and its radius one simple app... |
8,775 | circle circle _replace(radius= just as when we create circlethere is nothing to stop us from (or warn us aboutsetting invalid data if the circles were going to need lots of changeswe might opt to use mutable data type such as listfor the sake of conveniencecircle [ this doesn' give us any protection from putting in inv... |
8,776 | object-oriented programming appropriate to our class this will ensure that we never get conflicts with later versions of python even if they introduce new predefined special methods objects usually have attributes--methods are callable attributesand other attributes are data for examplea complex object has imag and rea... |
8,777 | object-oriented programming some object-oriented languages have two features that python does not provide the first is overloadingthat ishaving methods with the same name but with different parameter lists in the same class thanks to python' versatile argument-handling capabilities this is never limitation in practice ... |
8,778 | def __init__(selfx= = )self self def distance_from_origin(self)return math hypot(self xself ydef __eq__(selfother)return self =other and self =other def __repr__(self)return "point({ ! }{ ! })format(selfdef __str__(self)return "({ ! }{ ! })format(selfsince no base classes are specifiedpoint is direct subclass of object... |
8,779 | object-oriented programming object __new__(__init__(__eq__(__repr__(__str__(key inherited implemented reimplemented point __new__(__init__(distance_from_origin(__eq__(__repr__(__str__(figure the point class' inheritance hierarchy to create an objecttwo steps are necessary first raw or uninitialized object must be creat... |
8,780 | def __init__(selfx= = )self self the two instance variablesself and self yare created in the initializerand assigned the values of the and parameters since python will find this initializer when we create new point objectthe object __init__(method will not be called this is because as soon as python has found the requi... |
8,781 | object-oriented programming table comparison special methods special method usage description __lt__(selfotherx __le__(selfotherx < returns true if is less than or equal to __eq__(selfotherx = returns true if is equal to __ne__(selfotherx ! returns true if is not equal to __ge__(selfotherx > returns true if is greater ... |
8,782 | shape point( repr(pq eval( __module__ repr( )repr(qimport returns'point( )returns'point( )we must give the module name when eval()-ing if we used import shape (this would not be necessary if we had done the import differentlyfor examplefrom shape import point python provides every object with few private attributesone ... |
8,783 | of its computation since the circle class does not provide an implementation of the distance_from_origin(methodthe one provided by the point base class will be found and used contrast this with the reimplementation of the __eq__(method this method compares this circle' radius with the other circle' radiusand if they ar... |
8,784 | object-oriented programming using properties to control attribute access |in the previous subsection the point class included distance_from_origin(methodand the circle class had the area()circumference()and edge_distance_from_origin(methods all these methods return single float valueso from the point of view of user of... |
8,785 | in the previous subsection we noted that no validation is performed on the circle' radius attribute we can provide validation by making radius into property this does not require any changes to the circle __init__(methodand any code that accesses the circle radius attribute will continue to work unchanged--only now the... |
8,786 | object-oriented programming getter method by the @property decorator the other two are set up by python so that they do nothing (so the attribute cannot be written to or deleted)unless they are used as decoratorsin which case they in effect replace themselves with the method they are used to decorate the circle' initia... |
8,787 | |fuzzybool fuzzybool " ={ % ={ %}format(ab returnsfuzzybool( is nowfuzzybool( returns' = = %we want the fuzzybool type to support the complete set of comparison operators (=>)and the three basic logical operationsnot (~)and (&)and or (|in addition to the logical operations we want to provide couple of other logical met... |
8,788 | object __new__(__init__(__eq__(__repr__(__str__(__hash__(__format__(key inherited implemented reimplemented fuzzybool __value __new__(__init__(__eq__(__repr__(__str__(__hash__(__format__(__bool__(__float__(__invert__(__and__(__iand__(conjunction(static figure the fuzzybool class' inheritance hierarchy def __iand__(self... |
8,789 | object-oriented programming we have created an eval()-able representational form for examplegiven fuzzybool fuzzybool )repr(fwill produce the string 'fuzzybool( )all objects have some special attributes automatically supplied by pythonone of which is called __class__a reference to the object' class all classes have pri... |
8,790 | table numeric and bitwise special methods special method usage special method usage __abs__(selfabs(x__complex__(selfcomplex(x__float__(selffloat(x__int__(selfint(x__index__(selfbin(xoct(x__round__(selfhex(xdigitsround(xdigits__pos__(self+ __neg__(self- __add__(selfotherx __sub__(selfotherx __iadd__(selfotherx + __isub... |
8,791 | object-oriented programming by defaultinstances of custom classes support operator =(which always returns false)and are hashable (so can be dictionary keys and can be added to setsbut if we reimplement the __eq__(special method to provide proper equality testinginstances are no longer hashable this can be fixed by prov... |
8,792 | the built-in staticmethod(function is designed to be used as decorator as we have done here static methods are simply methods that do not get self or any other first argument specially passed by python the operator can be chainedso given fuzzybool' fgand hwe can get the conjunction of all of them by writing this works ... |
8,793 | object-oriented programming creating data types from other data types the fuzzybool implementation in this subsubsection is in the file fuzzyboolalt py one immediate difference from the previous version is that instead of providing static methods for conjunction(and disjunction()we have provided them as module function... |
8,794 | the __new__(method is called before any object has been created (since object creation is what __new__(does)so it cannot have self object passed to it since one doesn' yet exist in fact__new__(is class method--these are similar to normal methods except that they are called on the class rather than on an instance and py... |
8,795 | object-oriented programming directly as though they were floats we have omitted the or versions since they differ only in their names (__or__(and __ior__()and that they use max(rather than min(def __repr__(self)return ("{ }({ })format(self __class__ __name__super(__repr__())we must reimplement the __repr__(method since... |
8,796 | alternative to raising notimplementederror exceptionespecially if we want to more closely mimic the behavior of python' built-in classesis to raise typeerror here is how we can make fuzzybool __add__(behave just like built-in classes that are faced with an invalid operationdef __add__(selfother)raise typeerror("unsuppo... |
8,797 | object-oriented programming the built-in exec(function dynamically executes the code passed to it from the object it is given in this case we have given it stringbut it is also possible to pass some other kinds of objects by defaultthe code is executed in the context of the enclosing scopein this case within the defini... |
8,798 | the built-in behavior here is the code that is generated for the first tuple ("__xor__""^")def __xor__(self*args)types ["'arg __class__ __name__ "'for arg in argsraise typeerror("unsupported operand type(sfor ^"'{self}'{join{args}formatself=self __class__ __name__join=(andif len(args= else ",")args="join(types))the two... |
8,799 | object-oriented programming potentially more efficient approach an image stores single background colorplus the colors of those points in the image that differ from the background color this is done by using dictionary as kind of sparse arraywith each key being an (xycoordinate and the corresponding value being the col... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.