id
int64
0
25.6k
text
stringlengths
0
4.59k
4,200
this method of using polyfit to find model for data works when the relationship can be described by an equation of the form baseax+ if used on data that cannot be described this wayit will yield erroneous results to see thislet' try replacing the body of the function byreturn *( **( * ) it now printsf( predicted ( when...
4,201
"if you can' prove what you want to provedemonstrate something else and pretend they are the same thing in the daze that follows the collision of statistics with the human mindhardly anyone will notice the difference " statistical thinking is relatively new invention for most of recorded history things were assessed qu...
4,202
balanced one anotherand led to the same conclusion as if they were all correct calhoun' (perhaps willfullyspurious response to adams was based on classical errorthe assumption of independence were he more sophisticated mathematicallyhe might have said something like" believe that the measurement errors are unbiased and...
4,203
liesdamned liesand statistics designer used linear scale and narrow range of pricesso the sizes of the changes were exaggerated the code in figure produces the two plots we looked at above and plot intended to give an accurate impression of the movement of housing prices it uses two plotting facilities that we have not...
4,204
the call plothousing('fair'produces the plot cum hoc ergo propter hoc it has been shown that college students who regularly attend class have higher average grades than students who attend class only sporadically those of us who teach these classes would like to believe that this is because the students learn something...
4,205
liesdamned liesand statistics we have not considered that causes each in factas it happensthe flu virus survives considerably longer in cool dry air than it does in warm wet airand in north america both the flu season and school sessions are correlated with cooler and dryer weather given enough retrospective datait is ...
4,206
liesdamned liesand statistics these four data sets are statistically similar they have the same mean value for ( )the same mean value for ( )the same variance for ( )the same variance for ( )and the same correlation between and ( furthermoreif we use linear regression to fit line to eachwe get the same result for eachy...
4,207
liesdamned liesand statistics sampling bias during world war iiwhenever an allied plane would return from mission over europe the plane would be inspected to see where the flak had impacted based upon this datamechanics reinforced those areas of the planes that seemed most likely to be hit by flak what' wrong with this...
4,208
pretty scary stuff if your sexual preference is other than heterosexual--until one looks at how the data was compiled according to the web site it was based on " , obituaries from homosexual journalscompared to obituaries from mainstream newspapers this method produces sample that could be non-representative of either ...
4,209
liesdamned liesand statistics consider the plot on the left it shows the growth of internet usage in the united states from to as you can seea straight line provides pretty good fit the plot on the right uses this fit to project the percentage of the population using the internet in following years the projection is bi...
4,210
march and june there were more anorexics born than averageand more in june itself let' look at that worrisome statistic for those women born in june the team studied women who had been diagnosed as anorexicso the mean number of births per month was slightly more than this suggests that the number born in june was ( * l...
4,211
liesdamned liesand statistics the call anyprob( printed probability of at least births in some month it appears that it is not so unlikely after all that the results reported in the study reflect chance occurrence rather real association between birth month and anorexia one doesn' have to come from texas to fall victim...
4,212
percentages can be particularly misleading when applied to small basis you might read about drug that has side effect of increasing the incidence of some illness by but if the base incidence of the disease is very lowsay one in , , you might well decide that the risk of taking the drug was more than counterbalanced by ...
4,213
the notion of an optimization problem provides structured way to think about solving lots of computational problems whenever you set about solving problem that involves finding the biggestthe smallestthe mostthe fewestthe fastestthe least expensiveetc there is good chance that you can map the problem onto classic optim...
4,214
knapsack and graph optimization problems suppose for examplea burglar who has knapsack that can hold at most pounds of loot breaks into house and finds the items in figure clearlyhe will not be able to fit it all in his knapsackso he needs to decide what to take and what to leave behind value weight value/weight clock ...
4,215
knapscak and graph optimization problems the only interesting code is the implementation of the function greedy by introducing the parameter keyfunctionwe make greedy independent of the order in which the elements of the list are to be considered all that is required is that keyfunction defines an ordering on the eleme...
4,216
def greedy(itemsmaxweightkeyfunction)"""assumes items listmaxweight > keyfunction maps elements of items to floats""itemscopy sorted(itemskey=keyfunctionreverse trueresult [totalvalue totalweight for in range(len(itemscopy))if (totalweight itemscopy[igetweight()<maxweightresult append(itemscopy[ ]totalweight +itemscopy...
4,217
knapscak and graph optimization problems function is roughly ( log )where is the length of the list to be sorted therefore the running time of greedy is ( log nan optimal solution to the / knapsack problem suppose we decide that an approximation is not good enoughi we want the best possible solution to this problem suc...
4,218
def choosebest(psetmaxweightgetvalgetweight)bestval bestset none for items in psetitemsval itemsweight for item in itemsitemsval +getval(itemitemsweight +getweight(itemif itemsweight bestvalbestval itemsval bestset items return (bestsetbestvaldef testbest(maxweight )items builditems(pset genpowerset(itemstakenval choos...
4,219
knapscak and graph optimization problems some metriclocal choice at each step it makes choice that is locally optimal howeveras this example illustratesa series of locally optimal decisions does not always lead to solution that is globally optimal despite the fact that they do not always find the best solutiongreedy al...
4,220
knapsack and graph optimization problems graphs are typically used to represent situations in which there are interesting relations among the parts the first documented use of graphs in mathematics was in when the swiss mathematician leonhard euler used what has come to be known as graph theory to formulate and solve t...
4,221
knapscak and graph optimization problems can represent any road map (including those with one-way streetsby weighted digraph similarlythe structure of the world wide web can be represented as digraph in which the nodes are web pages and there is an edge from node to node if and only if there is link to page on page tra...
4,222
figure contains implementations of the classes digraph and graph one important decision is the choice of data structure used to represent digraph one common representation is an adjacency matrixwhere is the number of nodes in the graph each cell of the matrix contains information ( weightsabout the edges connecting the...
4,223
knapscak and graph optimization problems you might want to stop for minute and think about why graph is subclass of digraphrather than the other way around in many of the examples of subclassing we have looked atthe subclass adds attributes to the superclass for exampleclass weightededge added weight attribute to class...
4,224
the spread of disease and min cut figure contains pictorial representation of weighted graph generated by the centers for disease control (cdcin the course of studying an outbreak of tuberculosis in the united states each node represents personand each node is labeled by color indicating whether the person has active t...
4,225
knapscak and graph optimization problems in order to best limit the continued spreadwhich uninfected people should be vaccinatedthis can be formalized as solving min cut problem let na be the set of active tb nodes and no be the set of all the other nodes each edge in the minimum cut between these two sets will contain...
4,226
exploredit chooses the shortest path (assuming that there is onefrom the start to the goal the code is bit more complicated than the algorithm we just described because it has to deal with the possibility of the graph containing cycles it also avoids exploring paths longer than the shortest path that it has already fou...
4,227
knapscak and graph optimization problems def printpath(path)"""assumes path is list of nodes""result 'for in range(len(path))result result str(path[ ]if !len(path result result '->return result def dfs(graphstartendpathshortest)"""assumes graph is digraphstart and end are nodespath and shortest are lists of nodes retur...
4,228
when executedtestsp produces the output current dfs path current dfs path -> current dfs path -> -> current dfs path -> -> -> current dfs path -> -> -> -> current dfs path -> -> -> -> current dfs path -> -> -> current dfs path -> current dfs path -> -> current dfs path -> -> -> current dfs path -> -> -> current dfs pat...
4,229
knapscak and graph optimization problems def bfs(graphstartend)"""assumes graph is digraphstart and end are nodes returns shortest path from start to end in graph""initpath [startpathqueue [initpathwhile len(pathqueue! #get and remove oldest element in pathqueue tmppath pathqueue pop( print 'current bfs path:'printpath...
4,230
comfortinglyeach algorithm found path of the same length in this casethey found the same path howeverif graph contains more than one shortest path between pair of nodesdfs and bfs will not necessarily find the same shortest path as mentioned abovebfs is convenient way to search for path with the fewest edges because th...
4,231
dynamic programming was invented by richard bellman in the early don' try to infer anything about the technique from its name as bellman described itthe name "dynamic programmingwas chosen to hide from governmental sponsors "the fact that was really doing mathematics [the phrase dynamic programmingwas something not eve...
4,232
dynamic programming while this implementation of the recurrence is obviously correctit is terribly inefficient tryfor examplerunning fib( )but don' wait for it to complete the complexity of the implementation is bit hard to derivebut it is roughly (fib( )that isits growth is proportional to the growth in the value of t...
4,233
dynamic programming def fastfib(nmemo {})"""assumes is an int > memo used only by recursive calls returns fibonacci of ""if = or = return tryreturn memo[nexcept keyerrorresult fastfib( - memofastfib( - memomemo[nresult return result figure implementing fibonacci using memo if you try running fastfibyou will see that it...
4,234
dynamic programming the elements of the quadruple area set of items to be takenthe list of items for which decision has not been madethe total value of the items in the set of items to be taken (this is merely an optimizationsince the value could be computed from the set)and the remaining space in the knapsack (againth...
4,235
dynamic programming figure decision tree for knapsack problem the root of the tree (node has label indicating that no items have been takenall items remain to be consideredthe value of the items taken is and weight of is still available node indicates that has been taken[ , ,dremain to be consideredthe value of the ite...
4,236
notice that the implementation of maxval does not build the decision tree and then look for an optimal node insteadit uses the local variable result to record the best solution found so far def maxval(toconsideravail)"""assumes toconsider list of itemsavail weight returns tuple of the total weight of solution to the / ...
4,237
dynamic programming bigtest( after you get tired of waiting for it to returnstop it and ask yourself what is going on def buildmanyitems(numitemsmaxvalmaxweight)items [for in range(numitems)items append(item(str( )random randint( maxval)random randint( maxweight))return items def bigtest(numitems)items buildmanyitems(n...
4,238
the code in figure exploits the optimal substructure and overlapping subproblems to provide dynamic programming solution to the / knapsack problem an extra parametermemohas been added to keep track of solutions to subproblems that have already been solved it is implemented using dictionary with key constructed from the...
4,239
dynamic programming number of calls number of items selected , , , , len(items figure performance of dynamic programming solution the growth is hard to quantifybut it is clearly far less than exponential but how can this besince we know that the / knapsack problem is inherently exponential in the number of itemshave we...
4,240
to see what happens when the the values of avail are chosen from considerably larger spacechange the call to fastmaxval in figure to valtaken fastmaxval(items finding solution now takes , , calls of fastmaxval when the number of items is to see what happens when the weights are chosen from an enormous spacewe can choos...
4,241
the amount of digital data in the world has been growing at rate that defies human comprehension the world' data storage capacity has doubled about every three years since the during the time it will take you to read this approximately bits of data will be added to the world' store it' not easy to relate to number that...
4,242
supposefor exampleyou were given the following two sets of peoplea{abraham lincolngeorge washingtoncharles de gaulleb{benjamin harrisonjames madisonlouis napoleonnowsuppose that you were provided with the following partial descriptions of each of themabraham lincolnamericanpresident cm tall george washingtonamericanpre...
4,243
quick look at machine learning in unsupervised learningwe are given set of feature vectors but no labels the goal of unsupervised learning is to uncover latent structure in the set of feature vectors for examplegiven the set of presidential feature vectorsan unsupervised learning algorithm might separate the presidents...
4,244
quick look at machine learning unsupervised learningthe problem is harder typicallywe choose features based upon our intuition about which features might be relevant to the kinds of structure we would like to find consider figure which contains table of feature vectors and the label (reptile or notwith which each vecto...
4,245
quick look at machine learning had included the fact that reptile eggs have amnios, we could devise rule that separates reptiles from fish unfortunatelyin most practical applications of machine learning it is not possible to construct feature vectors that allow for perfect discrimination does this mean that we should g...
4,246
easily see that the star is units from the circle these distances are called euclidean distancesand correspond to using the minkowski distance with but imagine that the lines in the picture correspond to streetsand that one has to stay on the streets to get from one place to another in that casethe star remains units f...
4,247
quick look at machine learning def compareanimals(animalsprecision)"""assumes animals is list of animalsprecision an int > builds table of euclidean distance between each animal""#get labels for columns and rows columnlabels [for in animalscolumnlabels append( getname()rowlabels columnlabels[:tablevals [#get distances ...
4,248
if we run the code rattlesnake animal('rattlesnake'[ , , , , ]boa animal('boa\nconstrictor'[ , , , , ]dartfrog animal('dart frog'[ , , , , ]animals [rattlesnakeboadartfrogcompareanimals(animals it produces figure containing the table as you probably expectedthe distance between the rattlesnake and the boa constrictor i...
4,249
quick look at machine learning happens if we turn the feature into binary featurewith value of if the animal is legless and otherwise this looks lot more plausible of courseit is not always convenient to use only binary features in section we will present more general approach to dealing with differences in scale among...
4,250
quick look at machine learning first compute the mean of the feature vectors of all the examples in the cluster if is list of feature vectors each of which is an array of numbersthe mean (more precisely the euclidean meanis the value of the expression sum( )/float(len( )given the mean and metric for computing the dista...
4,251
quick look at machine learning types example and cluster class example will be used to build the samples to be clustered associated with each example is namea feature vectorand an optional label the distance method returns the euclidean distance between two examples class example(object)def __init__(selfnamefeatureslab...
4,252
quick look at machine learning class cluster(object)def __init__(selfexamplesexampletype)"""assumes examples is list of example of type exampletype""self examples examples self exampletype exampletype self centroid self computecentroid(def update(selfexamples)"""replace the examples in the cluster by new examples retur...
4,253
quick look at machine learning -means clustering -means clustering is probably the most widely used clustering method its goal is to partition set of examples into clusters such that each example is in the cluster whose centroid is the closest centroid to that exampleand the dissimilarity of the set of clusters is mini...
4,254
def kmeans(examplesexampletypekverbose)"""assumes examples is list of examples of type exampletypek is positive intverbose is boolean returns list containing clusters if verbose is true it prints result of each iteration of -means""#get randomly chosen initial centroids initialcentroids random sample(examplesk#create s...
4,255
quick look at machine learning def dissimilarity(clusters)totdist for in clusterstotdist + variance(return totdist def trykmeans(examplesexampletypenumclustersnumtrialsverbose false)"""calls kmeans numtrials times and returns the result with the lowest dissimilarity""best kmeans(examplesexampletypenumclustersverbosemin...
4,256
def gendistribution(xmeanxsdymeanysdnnameprefix)samples [for in range( ) random gauss(xmeanxsdy random gauss(ymeanysdsamples append(example(nameprefix+str( )[xy])return samples def plotsamples(samplesmarker)xvalsyvals [][for in samplesx getfeatures()[ getfeatures()[ pylab annotate( getname()xy (xy)xytext ( + - )fontsiz...
4,257
quick look at machine learning and printed iteration cluster with centroid contains cluster with centroid contains iteration cluster with centroid contains cluster with centroid contains iteration cluster with centroid contains cluster with centroid contains iteration cluster with centroid contains cluster with centroi...
4,258
(with respect to minimizing the objective functionas one of the solutions found using trials finger exercisedraw lines on figure to show the separations found by our two attempts to cluster the points do you agree that the solution found using trials is better than the one found using trialone of the key issues in usin...
4,259
quick look at machine learning the invocation contrivedtest ( falseprints final result cluster with centroid contains cluster with centroid contains cluster with centroid contains and the invocation contrivedtest ( falseprints final result cluster with centroid cluster with centroid cluster with centroid cluster with c...
4,260
the table on the right shows the contents of file listing some species of mammalstheir dental formulas (the first numbers)their average adult weight in pounds, and code indicating their preferred diet the comments at the top describe the items associated with each mammale the first item following the name is the number...
4,261
quick look at machine learning the last part of readmammaldata uses the values in featurevals to create list of feature vectorsone for each mammal (the code could be simplified by not constructing featurevals and instead directly constructing the feature vectors for each mammal we chose not to do that in anticipation o...
4,262
def buildmammalexamples(featurelistlabellistspeciesnames)examples [for in range(len(speciesnames))features pylab array(featurelist[ ]example example(speciesnames[ ]featureslabellist[ ]examples append(examplereturn examples def testteeth(numclustersnumtrials)featureslabelsspecies readmammaldata('dentalformulas txt'examp...
4,263
quick look at machine learning this is common problemwhich is often addressed by scaling the features so that each feature has mean of and standard deviation of as done by the function scalefeatures in figure def scalefeatures(vals)"""assumes vals is sequence of numbers""result pylab array(valsmean sum(result)/float(le...
4,264
quick look at machine learning def readmammaldata(fnamescale)"""assumes scale is boolean if truefeatures are scaled""#start of code is same as in previous version #use featurevals to build list containing the feature vectors #for each mammal scale featuresif needed if scalefor in range(numfeatures)featurevals[iscalefea...
4,265
quick look at machine learning the clustering with scaling does not perfectly partition the animals based upon their eating habitsbut it is certainly correlated with what the animals eat it does good job of separating the carnivores from the herbivoresbut there is no obvious pattern in where the omnivores appear this s...
4,266
common operations on numerical types + is the sum of and - is minus * is the product of and // is integer division / is divided by in python when and are both of type intthe result is also an intotherwise the result is float % is the remainder when the int is divided by the int ** is raised to the power + is equivalent...
4,267
python quick reference common list methods append(eadds the object to the end of count(ereturns the number of times that occurs in insert(ieinserts the object into at index extend( appends the items in list to the end of remove(edeletes the first occurrence of from index(ereturns the index of the first occurrence of in...
4,268
__init__ __lt__ built--in method __name__ built--in method __str__ abs built--in function abstract data type see data abstraction abstraction abstraction barrier acceleration due to gravity algorithm aliasing testing for al--khwarizmimuhammad ibn musa american folk art museum annotatepylab plotting anscombef append met...
4,269
index type xrange byte ++ cartesian coordinates case--sensitivity causal nondeterminism centroid child node churchalonzo church--turing thesis chutes and ladders class variable classes - __init__ method __name__ method __str__ method abstract attribute attribute reference class variable data attribute defining definiti...
4,270
index defensive programming dental formula depth--first search (dfs) destination node deterministic program dict type - adding an element allowable keys deleting an element keys keys method values method dictionary see dict type dijkstraedsger dimensionalityof data disjunct dispersion dissimilarity metric distributions...
4,271
index writing first--class values fitting curve to data - coefficient of determination ( ) exponential with polyfit least--squares objective function linear regression objective function, overfitting polyfit fixed--program computers float type see floating point floating point - exponent precision reals vs rounded valu...
4,272
index edit menu file menu if statement immutable type import statement in operator indentation of code independent events indexing for sequence types indirection induction inductive definition inferential statistics information hiding input input built--in function raw_input vs instanceof class integrated development e...
4,273
- label 'posif else 'negprint(labelneg in [ ]print('posif else 'neg'neg basic types string strings in python are immutable in [ ]string 'my stringstring[ 'ttypeerror traceback (most recent call lastin string 'my string---- string[ 'ttypeerror'strobject does not support item assignment in [ ]string replace(' '' 'out[ ]'...
4,274
from datetime import date 'today is str(date today()out[ ]'today is in [ ]'today is {and number {format(date today()[ ]out[ ]'today is and number [ -strings have been introduced in python in [ ]print( 'today is {date today()}'today is check if substring is in string in [ ]if 'subin 'substring'print('true'true there are...
4,275
['__add__''__class__''__contains__''__delattr__''__delitem__''__dir__''__doc__''__eq__''__format__''__ge__''__getattribute__''__getitem__''__gt__''__hash__''__iadd__''__imul__''__init__''__init_subclass__''__iter__''__le__''__len__''__lt__''__mul__''__ne__''__new__''__reduce__''__reduce_ex__''__repr__''__reversed__''__...
4,276
'__len__''__lt__''__mod__''__mul__''__ne__''__new__''__reduce__''__reduce_ex__''__repr__''__rmod__''__rmul__''__setattr__''__sizeof__''__str__''__subclasshook__''capitalize''casefold''center''count''encode''endswith''expandtabs''find''format''format_map''index''isalnum''isalpha''isdecimal''isdigit''isidentifier''islowe...
4,277
enum is data type which links name to an index they are useful to represent closed set of options in [ ]from enum import enum class qhbrowseraction(enum)query_button_clicked save_button_clicked date_changed qh_name_changed slider_moved qhbrowseraction date_changed namea value out[ ]('date_changed' in [ ]a_next qhbrowse...
4,278
my_list[ my_list out[ ][ truein order to extend list one can either append in [ ]my_list append( my_list out[ ][ true or simply in [ ]my_list [ ' 'out[ ][ true ' 'or append elements in ]my_list +[ my_list in ]my_list my_list [ one shall not do that my_list be careful with the last assignmentthis creates new listso need...
4,279
import itertools list [[ , , ][ , , ][ ][ , ]merged list(itertools chain(*list )merged out[ ][[ ][ ][ ][ ]which one to choose in order to add elements efficientlylist comprehension old-fashioned way in [ ]my_list [for in range( )my_list append(imy_list out[ ][ one-line list comprehension in [ ]abs( () - out[ ]true in [...
4,280
( ** for in range( )print(xat faceb in [ ]next(xstopiteration traceback (most recent call lastin ---- next(xstopiterationin [ ]import datetime str(datetime datetime now()out[ ] : : in [ ]print(datetime datetime now()for in (( + )** for in range(int( ))) **(- / print(datetime datetime now() : : : : in [ ]print(datetime ...
4,281
my_list [- - - - - filter(lambda xx> my_listout[ ]filter returns an iterable generator generator is very important concept in pythonin [ ]for el in filter(lambda xx> ,my_list)print(el in [ ]list(filter(lambda xx> my_list)out[ ][ map in [ ]print(my_listlist(map(lambda xabs( )my_list)[- - - - - out[ ][ map can be applied...
4,282
from functools import reduce reduce(lambda xyx+ [ , , , , , , , , , , ]out[ ] $ + + \frac{ ( + )}{ }iterating over lists in [ ] for el in [- - - - - ]print(ieli + - - - - - iterating with index in [ ]for indexel in enumerate([- - - - - ])print(indexel - - - - - iterating over two (manylists in [ ]letters [' '' '' '' 'n...
4,283
list(zip(lettersnumbers)out[ ][(' ' )(' ' )(' ' )(' ' )in [ ]dict(zip(lettersnumbers)out[ ]{' ' ' ' ' ' ' ' in [ ]help(ziphelp on class zip in module builtinsclass zip(objectzip(iter [,iter ]]--zip object return zip object whose __next__(method returns tuple where the -th element comes from the -th iterable argument th...
4,284
[ copy( [ 'aprint(xy[ [' ' in [ ] [[ ' '] copy(equivalent to [: [ 'aprint(xy[[ ' '] [' ' in [ ] [[ ' '] copy( [ ][ 'bprint(xy[[' '' '] [[' '' '] the reason for this behavior is that python performs shallow copy in [ ]from copy import deepcopy [[ ' '] deepcopy(xy[ ][ 'bprint(xy[[ ' '] [[' '' '] sorting lists inplace ope...
4,285
[ sorted(xprint( [ in [ ] [ is sorted(xout[ ]false how to sort in reverted order in [ ] [ sort(reverse=trueprint( [ sort nested lists in [ ]employees [( 'john')( 'emily')( 'david')( 'mark')( 'andrew')employees sort(key=lambda xx[ ]employees out[ ][( 'andrew')( 'mark')( 'john')( 'emily')( 'david')in [ ]employees [( 'joh...
4,286
my_list *[' 'my_list out[ ][' '' '' '' '' 'in [ ] in [ , , , , out[ ]true in [ ] [' ' [' ' = out[ ]true in [ ] (' ' (' ' is out[ ]true tuples tuplessimilarly to lists can stores elements of different types in [ ]my_tuple ( , , my_tuple out[ ]( in [ ]my_tuple[ out[ ] unlike the liststuples are immutable in [ ]my_tuple[ ...
4,287
tuple([ , , ]out[ ]( sets sets are immutable and contain only unique elements in [ ]{ , , , out[ ]{ in [ ]{ , , , , out[ ]{ so this is neat way for obtaining unique elements in list in [ ]my_list [ set(my_listout[ ]{ or tuple in [ ]my_tuple ( set(my_tupleout[ ]{ one can perform set operations on sets ;-in [ ] { , , { ,...
4,288
pm {'system''source''i_meas''i_ref'signals pm {'system''source'signals out[ ]{'i_meas''i_ref'in [ ]for in signalsprint(si_meas i_ref in [ ]help(sethelp on class set in module builtinsclass set(objectset(-new empty set object set(iterable-new set object build an unordered collection of unique elements methods defined he...
4,289
return len(self__lt__(selfvalue/return self<value __ne__(selfvalue/return self!=value __new__(*args**kwargsfrom builtins type create and return new object see help(typefor accurate signature __or__(selfvalue/return self|value __rand__(selfvalue/return value&self __reduce__return state information for pickling __repr__(...
4,290
isdisjointreturn true if two sets have null intersection issubsetreport whether another set contains this set issupersetreport whether this set contains another set popremove and return an arbitrary set element raises keyerror if the set is empty removeremove an element from setit must be member if the element is not m...
4,291
firstsecond [ print(firstsecondvalueerror traceback (most recent call lastin ---- firstsecond [ print(firstsecondvalueerrortoo many values to unpack (expected in [ ]firstsecond ( print(firstsecond in [ ]firstsecond { print(firstsecond in [ ]employees [( 'john')( 'emily')( 'david')( 'mark')( 'andrew')for employee_idempl...
4,292
my_dict[' 'out[ ] in [ ]for key in my_dictprint(keya in [ ]for keyvalue in my_dict items()print(keyvaluea summary of python containers feature list tuple dict set purpose an ordered collection of variables an ordered collection of variables an ordered collection of key,value pairs collection of variables duplication of...
4,293
def (abc= )return + + ( , out[ ] in [ ] ( , out[ ] if the number of arguments matchesone can pass list in [ ]lst [ , , (*lstout[ ] or dictionary (provided that key names match the argument namesvery useful for methods with multiple argumentse plottingquerying databasesetc in [ ]dct {' ' ' ' ' ' (**dctout[ ] in ]query_p...
4,294
def (**kwargs)return kwargs[' 'kwargs[' ' ( = = = out[ ] in [ ]def (arg*args**kwargs)return arg sum(argskwargs[' ' ( = out[ ] in [ ]def (ab* )return + + ( , , typeerror traceback (most recent call lastin def (ab* ) return + + ---- ( , , typeerrorf(takes positional arguments but were given in [ ] ( , ,scaling= out[ ] fu...
4,295
first list( ()print(firstprint(secondin [ ]first[ in [ ]first out[ ][' ' ' ' recursion factorial of an integer $nis given as\begin{equationnn*( - )*( - )*( - ) \end{equationfor example\begin{equation \end{equationin [ ]def factorial( )if = return elsereturn *factorial( - factorial( out[ ] in [ ]factorial( out[ ] in [ ]...
4,296
file "/usr/local/lib/swan/ipython/core/interactiveshell py"line in run_code exec(code_objself user_global_nsself user_nsfile ""line in factorial(- file ""line in factorial return *factorial( - file ""line in factorial return *factorial( - file ""line in factorial return *factorial( - [previous line repeated more timesf...
4,297
in [ ]def flatten_nested_lists( )result [for el in xif isinstance(el(listtuple))result extend(flatten_nested_lists(el)elseresult append(elreturn result in [ ]lst [ lst [ lst append(lst lst typeerror traceback (most recent call lastin lst [ lst [ ---- lst append(*lst lst typeerrorappend(takes exactly one argument ( give...
4,298
arguments [def fib( )arguments append(nif = return elif = return elsereturn fib( - fib( - [fib(ifor in range( )print( [ in [ ]counts {iarguments count(ifor in range(max(arguments)+ )counts out[ ]{ in [ ]sum(counts values()out[ ] memoization in computingmemoization or memoisation is an optimization technique used primar...
4,299
sum(counts values()out[ ] decorators decorators are functions dedicated to enhance functionality of given functione check parameter inputsformat input in [ ]def argument_test_natural_number( )def helper( )if type(xis int and return (xelseraise exception("argument is not an integer"return helper def factorial( )if = ret...