id
int64
0
25.6k
text
stringlengths
0
4.59k
13,500
stringslike all sequence typessupport indexing and slicing we can retrieve any character from string by using its index [iwe can retrieve slice of string by using [ : ]where and are the start and end points of the slice we can return an extended slice by using strideas in the followings[ : :stridethe following code sho...
13,501
given that strings are immutablea common question that arises is how we perform operations such inserting values rather than changing stringwe need to think of ways to build new string objects for the results we need for exampleif we wanted to insert word into our greetingwe could assign variable to the followingas thi...
13,502
insert( ,einserts at index pop(ireturns the element and removes it from the list remove(xremoves from reverse(reverses the order of sort(key ,[reverse]sorts with optional key and reverse when we are working with listsand other container objectsit is important to understand the internal mechanism that python uses to cop...
13,503
common and very intuitive way to create lists from expressions is using list comprehensions this allows us to create list by writing an expression directly into the listfor examplelist comprehensions can be quite flexiblefor exampleconsider the following code it essentially shows two different ways to performs function...
13,504
list comprehensions can also be used to replicate the action of nested loops in more compact form for examplewe multiply each of the elements contained within list with each otherwe can also use list comprehensions with other objects such as stringsto build more complex structures for examplethe following code creates ...
13,505
to have look at how this workslet' define simple functiondef greeting(language)if language='eng'return 'hello worldif language ='frreturn 'bonjour le mondeelsereturn 'language not supportedsince user-defined functions are objectswe can do things such as include them in other objectssuch as listsfunctions can also be us...
13,506
higher order functions functions that take other functions as argumentsor that return functionsare called higher order functions python contains two built-in higher order functionsfilter(and map(note that in earlier versions of pythonthese functions returned listsin python they return an iteratormaking them much more e...
13,507
here is another example for case-insensitive sortingnote the difference between the list sort(method and the sorted built-in function list sort() method of the list objectsorts the existing instance of list without copying it this method changes the target object and returns none it is an important convention in python...
13,508
recursive functions recursion is one of the most fundamental concepts of computer science in pythonwe can implement recursive function simply by calling it within its own function body to stop recursive function turning into an infinite loopwe need at least one argument that tests for terminating case to end the recurs...
13,509
compares the running time of list compared to generator import time #generator function creates an iterator of odd numbers between and def oddgen(nm)while myield + #builds list of odd numbers between and def oddlst( , )lst=[while <mlst append(nn += return lst #the time it takes to perform sum on an iterator =time time(...
13,510
we can also create generator expressionwhichapart from replacing square brackets with parenthesesuses the same syntax and carries out the same operation as list comprehensions generator expressionshoweverdo not create listthey create generator object this object does not create the databut rather creates that data on d...
13,511
class employee(object)numemployee def __init__(selfnamerate)self owed self name name self rate=rate employee numemployee + def __del__(self)employee numemployee - def hours(selfnumhours)self owed +numhours self rate return(" hours workednumhoursdef pay(self)self owed return("payed % self nameclass variablessuch as nume...
13,512
special methods we can use the dir(objectfunction to get list of attributes of particular object the methods that begin and end with two underscores are called special methods apart from the following exceptionspecial methodare generally called by the python interpreter rather than the programmerfor examplewhen we use ...
13,513
inheritance it is possible to create new class that modifies the behavior of an existing class through inheritance this is done by passing the inherited class as an argument in the class definition it is often used to modify the behavior of existing methodsfor exampleclass specialemployee(employee)def hours(selfnumhour...
13,514
class methods operate on the class itselfnot the instancein the same way that class variables are associated with the classes rather than instances of that class they are defined using the @classmethod decoratorand are distinguished from instance methods in that the class is passed as the first argument this is named c...
13,515
it is recommended to use private attributes when using class property to define mutable attributes property is kind of attribute that rather than returning stored valuecomputes its value when called for examplewe could redefine the exp(property with the followingclass bexp(aexp)__base= def __exp(self)return( **cls base...
13,516
python data types and structures in this we are going to examine the python data types in detail we have already been introduced to two data typesthe stringstr()and list(it is often the case where we want more specialized objects to represent our data in addition to the built-in typesthere are several internal modules ...
13,517
boolean operations boolean operation returns value of eighter true or false boolean operations are ordered in priorityso if more than one boolean operation occurs in an expressionthe operation with the highest priority will occur first the following table outlines the three boolean operators in descending order of prio...
13,518
built-in data types python data types can be divided into three categoriesnumericsequenceand mapping there is also the none object that represents nullor absence of value it should not be forgotten either that other objects such as classesfilesand exceptions can also properly be considered typeshoweverthey will not be ...
13,519
set mutableunordered collection of unique items frozenset immutable set none type the none type is immutable and has one valuenone it is used to represent the absence of value it is returned by objects that do not explicitly return value and evaluates to false in boolean expressions it is often used as the default valu...
13,520
this is result of the fact that most decimal fractions are not exactly representable as binary fractionwhich is how most underlying hardware represents floating point numbers for algorithms or applications where this may be an issuepython provides decimal module this module allows for the exact representation of decima...
13,521
sequences sequences are ordered sets of objects indexed by non-negative integers lists and tuples are sequences of arbitrary objectsstrings are sequences of characters stringtupleand range objects are immutable all sequence types have number of operations in common for all sequencesthe indexing and slicing operators ap...
13,522
tuples tuples are immutable sequences of arbitrary objects they are indexed by integers greater than zero tuples are hashablewhich means we can sort lists of them and they can be used as keys to dictionaries syntacticallytuples are just comma-separated sequence of valueshoweverit is common practice to enclose them in p...
13,523
dictionaries dictionaries are arbitrary collections of objects indexed by numbersstringsor other immutable objects dictionaries themselves are mutablehowevertheir index keys must be immutable the following table contains all the dictionary methods and their descriptionsmethod description len(dnumber of items in clear(r...
13,524
we can add keys and values as followsd['four']= #add an item or update multiple values using the followingd update({'five' 'six' }#add multiple items when we inspect dwe get the followingwe can test for the occurrence of value using the in operatorfor exampleit should be noted that the in operatorwhen applied to dictio...
13,525
sorting dictionaries if we want to do simple sort on either the keys or values of dictionarywe can do the followingnote that the first line in the preceding code sorts the keys according to alphabetical orderand the second line sorts the values in order of integer value the sorted(method has two optional arguments that...
13,526
nowlet' say we are given the following dictionaryenglish words as keys and french words as values our task is to place these string values in correct numerical orderd ={'one':'uno'two':'deux''three':'trois''four''quatre''five''cinq''six':'six'of coursewhen we print this dictionary outit will be unlikely to print in the...
13,527
dictionaries for text analysis common use of dictionaries is to count the occurrences of like items in sequencea typical example is counting the occurrences of words in body of text the following code creates dictionary where each word in the text is used as key and the number of occurrences as its value this uses very...
13,528
note the use of the dictionary comprehension used to construct the filtered dictionary dictionary comprehensions work in an identical way to the list comprehensions we looked at in python objectstypesand expressions sets sets are unordered collections of unique items sets are themselves mutablewe can add and remove ite...
13,529
symmetric_difference(ts returns set of all items that are in or tbut not both union(treturns set of all items in or in the preceding tablethe parameter can be any python object that supports iteration and all methods are available to both set and frozenset objects it is important to be aware that the operator versions ...
13,530
the following example demonstrates some simple set operations and their resultsnotice that the set object does not care that its members are not all of the same typeas long as they are all immutable if you try to use mutable object such as list or dictionaries in setyou will receive an unhashable type error hashable ty...
13,531
immutable sets python has an immutable set type called frozenset it works pretty much exactly like set apart from not allowing methods or operations that change values such as the add(or clear(methods there are several ways that this immutability can be useful for examplesince normal sets are mutable and therefore not ...
13,532
so farwe have looked at the built-in datatypes of stringslistssetsand dictionaries as well as the decimal and fractions modules they are often described by the term abstract data types (adtsadts can be considered as mathematical specifications for the set of operations that can be performed on data they are defined by ...
13,533
the major advantage of deques over lists is that inserting items at the beginning of deque is much faster than inserting items at the beginning of listalthough inserting items at the end of deque is very slightly slower than the equivalent operation on list deques are threadsafe and can be serialized using the pickle m...
13,534
note that we can use the rotate and pop methods to delete selected elements also worth knowing is simple way to return slice of dequeas listwhich can be done as followsthe itertools islice method works in the same way that slice works on listexcept rather than taking list for an argumentit takes an iterable and returns...
13,535
chainmaps the collections chainmap class was added in python and it provides way to link number of dictionariesor other mappingsso that they can be treated as one object in additionthere is maps attributea new_child(methodand parents property the underlying mappings for chainmap objects are stored in list and are acces...
13,536
counter objects counter is subclass of dictionary where each dictionary key is hashable object and the associated value is an integer count of that object there are three ways to initialize counter we can pass it any sequence objecta dictionary of key:value pairsor tuple of the format (object value)for examplewe can al...
13,537
notice how the update method adds the counts rather than replacing them with new values once the counter is populatedwe can access stored values in the same way we would for dictionariesfor examplethe most notable difference between counter objects and dictionaries is that counter objects return zero count for missing ...
13,538
two other counter methods worth mentioning are most_common(and subtract(the most common method takes positive integer argument that determines the number of most common elements to return elements are returned as list of (key ,valuetuples the subtract method works exactly like update except instead of adding valuesit s...
13,539
the ordereddict is often used in conjunction with the sorted method to create sorted dictionary for examplein the following example we use lambda function to sort on the valueshere we use numerical expression to sort the integer valuesdefaultdict the defaultdict object is subclass of dict and therefore they share metho...
13,540
you will notice that if we tried to do this with an ordinary dictionarywe would get key error when we tried to add the first key the int we supplied as an argument to default dict is really the function int(that simply returns zero we canof coursecreate function that will determine the dictionary' values for examplethe...
13,541
the field names are passed to the namedtuple method as comma and/or whitespace separated values they can also be passed as sequence of strings field names are single strings and they can be any legal python identifier that does not begin with digit or an underscore typical example is shown herethe namedtuple method tak...
13,542
the _asdict method returns an ordereddict with the field names mapped to index keys and the values mapped to the dictionary valuesfor examplethe _replace method returns new instance of the tuplereplacing the specified valuesfor examplearrays the array module defines datatype array that is similar to the list datatype e...
13,543
'isigned int int 'iunsigned int int 'lsigned long int 'lunsigned long int 'qsigned long long int 'qunsigned lon long int 'ffloat float 'ddouble float the array objects support the following attributes and methodsattribute or method description typecode the typecode character used to create the array itemsize sizein byt...
13,544
pop([ ]removes and returns items with index defaults to the last item ( - if not specified remove(xremoves the first occurrence of item reverse(reverses the order of items tobytes(convert the array to machine values and returns the bytes representation tofile(fwrites all itemsas machine valuesto file object tolist(conv...
13,545
it should be noted that when performing operations on arrays that create listssuch as list comprehensionsthe memory efficiency gains of using an array in the first place will be negated when we need to create new data objecta solution is to use generator expression to perform the operationfor examplearrays created with...
13,546
principles of algorithm design why do we want to study algorithm designthere are of course many reasonsand our motivation for learning something is very much dependent on our own circumstances there are without doubt important professional reasons for being interested in algorithm design algorithms are the foundations ...
13,547
the study of algorithms is also important because it trains us to think very specifically about certain problems it can serve to increase our mental and problem solving abilities by helping us isolate the components of problem and define relationships between these components in summarythere are four broad reasons for ...
13,548
greedy algorithms often involve optimization and combinatorial problemsthe classic example is applying it to the traveling salesperson problemwhere greedy approach always chooses the closest destination first this shortest path strategy involves finding the best solution to local problem in the hope that this will lead...
13,549
this code prints out the digits to calculate requires four recursive calls plus the initial parent call on each recursiona copy of the methods variables is stored in memory once the method returns it is removed from memory the following is way we can visualize this processit may not necessarily be clear if recursion or...
13,550
backtracking backtracking is form of recursion that is particularly useful for types of problems such as traversing tree structureswhere we are presented with number of options at each nodefrom which we must choose one subsequently we are presented with different set of optionsand depending on the series of choices mad...
13,551
our aim here is to examine ways to measure how efficient this procedure is and attempt to answer the questionis this the most efficient procedure we can use for multiplying two large numbers togetherin the following figurewe can see that multiplying two digit numbers together requires multiplication operationsand we ca...
13,552
so now we can rewrite our multiplication problem xy as followswhen we expand and gather like terms we get the followingmore convenientlywe can write it like thiswhereit should be pointed out that this suggests recursive approach to multiplying two numbers since this procedure does itself involve multiplication specific...
13,553
when we subtract the quantities ac and bdwhich we have calculated in the previous recursive stepwe get the quantity we neednamely (ad bc)this shows that we can indeed compute the sum of ad bc without separately computing each of the individual quantities in summarywe can improve on equation by reducing from four recurs...
13,554
to satisfy ourselves that this does indeed workwe can run the following test functionimport random def test()for in range( ) random randint( , ** random randint( , ** expected result karatsuba(xyif result !expectedreturn("failed"return('ok'runtime analysis it should be becoming clear that an important aspect to algorit...
13,555
worst case analysis is useful because it gives us tight upper bound that our algorithm is guaranteed not to exceed ignoring small constant factorsand lower order terms is really just about ignoring the things thatat large values of the input sizendo not contributein large degreeto the overall run time not only does it ...
13,556
here is the python code for the merge sort algorithmdef mergesort( )#base case if the input array is one or zero just return if len( splitting input array print('splitting ' mid len( )// left [:midright [mid:#recursive calls to mergesort for left and right sub arrays mergesort(leftmergesort(right#initalizes pointers fo...
13,557
#assignment operation [ ]=left[ii= + = + while <len(right)#assignment operation [ ]=right[jj= + = + print('merging 'areturn(awe run this program for the following resultsthe problem that we are interested in is how we determine the running time performancethat iswhat is the rate of growth in the time it takes for the a...
13,558
each invocation of merge-sort subsequently creates two recursive callsso we can represent this with binary tree each of the child nodes receives sub set of the input ultimately we want to know the total time it takes for the algorithm to complete relative to the size of to begin with we can calculate the amount of work...
13,559
the advantage of using recursion tree to analyze algorithms is that we can calculate the work done at each level of the recursion how to define this work is simply as the total number of operations and this of course is related to the size of the input it is important to measure and compare the performance of algorithm...
13,560
importantly this shows thatbecause the cancels out the number of operations at each level is independent of the level this gives us an upper bound to the number of operations carried out on each levelin this example it should be pointed out that this includes the number of operations performed by each recursive call on...
13,561
in the previous examplemultiplying the nlog component and comparing it to notice how for very low values of nthe time to completet is actually lower for an algorithm that runs in time howeverfor values above about the log function begins to dominateflattening the output until at the comparatively moderate size the perf...
13,562
gives the following outputthe preceding graph shows the difference between counting six operations or seven operations we can see how the two cases divergeand this is important when we are talking about the specifics of an application howeverwhat we are more interested in here is way to characterize growth rates we are...
13,563
big notation the letter "oin big notation stands for orderin recognition that rates of growth are defined as the order of function we say that one function (nis big of another functionf( )and we define this as followsthe functiong( )of the input sizenis based on the observation that for all sufficiently large values of...
13,564
in the following tablewe list the most common growth rates in order from lowest to highest we sometimes call these growth rates the time complexity of functionor the complexity class of functioncomplexity class name example operations ( constant appendget itemset item (lognlogarithmic finding an element in sorted array...
13,565
the time complexity of this loop then becomes ( (no( ( here we are simply multiplying the time complexity of the operation with the number of times this operation executes the running time of loop is at most the running time of the statements inside the loop multiplied by the number of iterations single nested loopthat...
13,566
from this we can conclude that the total time (log( )although big is the most used notation involved in asymptotic analysisthere are two other related notations that should be briefly mentioned they are omega notation and theta notation omega notation (ohmin similar way that big notation describes the upper boundomega ...
13,567
amortized analysis often we are not so interested in the time complexity of individual operationsbut rather the time averaged running time of sequences of operations this is called amortized analysis it is different from average case analysiswhich we will discuss shortlyin that it makes no assumptions regarding the dat...
13,568
let' look at straightforward way to benchmark an algorithm' runtime performance this can be done by simply timing how long the algorithm takes to complete given various input sizes as we mentioned earlierthis way of measuring runtime performance is dependent on the hardware that it is run on obviously faster processors...
13,569
this gives the following resultsas we can seethis gives us pretty much what we expect it should be remembered that this represents both the performance of the algorithm itself as well as the behavior of underlying software and hardware platformsas indicated by both the variability in the measured runtime and the relati...
13,570
lists and pointer structures you will have already seen lists in python they are convenient and powerful normallyany time you need to store something in listyou use python' built-in list implementation in this howeverwe are more interested in understanding how lists work so we are going to study list internals as you w...
13,571
as it turns outthings are not very different in python land those large image files remain in one single place in memory what you do is create variables that hold the locations of those images in memory these variables are small and can easily be passed around between different functions that is the big benefit of poin...
13,572
pointer structures contrary to arrayspointer structures are lists of items that can be spread out in memory this is because each item contains one or more links to other items in the structure what type of links these are dependent on the type of structure we have if we are dealing with linked liststhen we will have li...
13,573
of courseknowing what we do about pointerswe realize that this is not entirely true the string is not really stored in the nodebut is rather pointer to the actual stringthus the storage requirement for this simple node is two memory addresses the data attribute of the nodes are pointers to the strings eggs and ham find...
13,574
node here is simple node implementation of what we have discussed so farclass nodedef __init__(selfdata=none)self data data self next none do not confuse the concept of node with node jsa server-side technology implemented in javascript the next pointer is initialized to nonemeaning that unless you change the value of ...
13,575
sometimes we want to go from to bbut at the same time from to in that casewe add previous pointer in addition to the next pointeras you can see from the figurewe let both the last and the first nodes point to noneto indicate that we have reached they form the boundary of our list end-point the first node' previous poin...
13,576
you can take this as far as you need to if you need to be able to move north-westnortheastsouth-eastand south-west as wellall you have to do is add these pointers to your node class singly linked lists singly linked list is list with only one pointer between two successive nodes it can only be traversed in single direc...
13,577
singly linked list class list is clearly separate concept from node so we start by creating very simple class to hold our list we will start with constructor that holds reference to the very first node in the list since this list is initially emptywe will start by setting this reference to noneclass singlylinkedlistdef...
13,578
we can append few itemswords singlylinkedlist(words append('egg'words append('ham'words append('spam'list traversal will work more or less like before you will get the first element of the list from the list itselfcurrent words tail while currentprint(current datacurrent current next faster append operation there is bi...
13,579
take note of the convention being used the point at which we append new nodes is through self head the self tail variable points to the first node in the list getting the size of the list we would like to be able to get the size of the list by counting the number of nodes one way we could do this is by traversing the e...
13,580
improving list traversal if you notice how we traverse our list that one place where we are still exposed to the node class we need to use node data to get the contents of the node and node next to get the next node but we mentioned earlier that client code should never need to interact with node objects we can achieve...
13,581
the following is figure of special case considered when deleting node from the listwhen we want to delete node that is between two other nodesall we have to do is make the previous node directly to the successor of its next node that iswe simply cut the node to be deleted out of the chain as in the preceding image
13,582
here is the implementation of the delete(method may look likedef delete(selfdata)current self tail prev self tail while currentif current data =dataif current =self tailself tail current next elseprev next current next self size - return prev current current current next it should take (nto delete node list search we m...
13,583
doubly linked lists now that we have solid grounding on what singly linked list is and the kind of operations that can be performed on itwe shall now turn our focus one notch higher to the topic of doubly linked lists doubly linked list is somehow similar to singly linked list in that we make use of the same fundamenta...
13,584
doubly linked lists can be traversed in any direction depending on the operation being performeda node within doubly linked list can easily refer to its previous node where necessary without having to designate variable to keep track of that node because singly linked list can only be traversed in one direction it may ...
13,585
we adopt new convention where self head points to the beginner node of the list and self tail points to the latest node added to the list this is contrary to the convention we used in the singly linked list there are no fixed rules as to the naming of the head and tail node pointers doubly linked lists also need to pro...
13,586
the else part of the algorithm is only executed if the list is not empty the new node' previous variable is set to the tail of the listnew_node prev self tail the tail' next pointer (or variableis set to the new nodeself tail next new_node lastlywe update the tail pointer to point to the new nodeself tail new_node sinc...
13,587
visual representation of the append operation is as followsdelete operation unlike the singly linked listwhere we needed to keep track of the previously encountered node anytime we traversed the whole length of the listthe doubly linked list avoids that whole step this is made possible by the use of the previous pointe...
13,588
in the delete methodthe current variable is set to the head of the list (that isit points to the self head of the lista set of if else statements are then used to search the various parts of the list to find the node with the specified data the head node is searched first since current is pointing at headif current is ...
13,589
the node_delete variable is then checked after all the if-else statements has been evaluated if any of the if-else statements changed this variablethen it means node has been deleted from the list the count variable is therefore decremented by if node_deletedself count - as an example of deleting node that is buried wi...
13,590
list search the search algorithm is similar to that of the search method in singly linked list we call the internal method iter(to return the data in all the nodes as we loop through the dataeach is matched against the data passed into the contain method if there is matchwe return trueor else we return false to symboli...
13,591
self head next node self head node elseself head node self tail node self head next self tail self size + deleting an element we may think that we can follow the same principle as for append and simply make sure the head points to the tail this would give us the following implementationdef delete(selfdata)current self ...
13,592
we thus need to find different way to control the while loop we cannot check whether current has reached headbecause then it will never check the last node but we could use prevsince it lags behind current by one node there is special casehowever the very first loop iterationcurrent and prevwill point to the same noden...
13,593
summary in this we have looked at linked lists we have studied the concepts that underlie listssuch as nodes and pointers to other nodes we implemented the major operations that occur on these types of list and saw how their worst case running times compare in the next we are going to look at two other data structures ...
13,594
stacks and queues in this we are going to build upon the skills we learned in the last in order to create special list implementations we are still sticking to linear structures we will get to more complex data structures in the coming in this we are going to look at the followingimplementing stacks and queues some app...
13,595
there are two primary operations that are done on stackspush and pop when an element is added to the top of the stackit is pushed onto the stack when an element is taken off the top of the stackit is popped off the stack another operation which is used sometimes is peekwhich makes it possible to see the element on the ...
13,596
when the code jumps into the functionthe values for abcd will be popped off the stack the spam element will be popped off first and assigned to dthen "hamwill be assigned to cand so ondef somefunc(abcd)print("function executed"stack implementation now let us study an implementation of stack in python we start off by cr...
13,597
in the following figurethere is no existing node after creating our new node thus self top will point to this new node the else part of the if statement guarantees that this happensin scenario where we have an existing stackwe move self top so that it points to the newly created node the newly created node must have it...
13,598
self size - if self top nextself top self top next elseself top none return data elsereturn none the thing to pay attention to here is the inner if statement if the top node has its next attribute pointing to another nodethen we must set the top of the stack to now point to that nodewhen there is only one node in the s...
13,599
peek as we said earlierwe could also add peek method this will just return the top of the stack without removing it from the stackallowing us to look at the top element without changing the stack itself this operation is very straightforward if there is top elementreturn its dataotherwise return none (so that the behav...