id
int64
0
25.6k
text
stringlengths
0
4.59k
12,500
my_list [ true my_list[ ]= ** my_list [ true my_name 'davidmy_name[ ]='xtraceback (most recent call last)file ""line in my_name[ ]='xtypeerror'strobject does not support item assignment note that the error (or tracebackmessage displayed above is obtained on mac os machine if you are running the above code snippet on wi...
12,501
operator in len <use in(setlen(setset set set set set set set <set explanation set membership returns the cardinality ( the lengthof the set returns new set with all elements from both sets returns new set with only the elements common to both sets returns new set with all items from the first set not in second asks wh...
12,502
method name use union set union(set explanation returns new set with all elements from both sets intersection set intersection(set returns new set with only the elements common to both sets difference set difference(set returns new set with all items from first set not in second issubset set issubset(set asks whether a...
12,503
operator [in del use explanation my_dict[kreturns the value associated with kotherwise its an error key in my_dict returns true if key is in the dictionaryfalse otherwise del my_dict[keyremoves the entry from the dictionary table operators provided by dictionaries in python our final python collection is an unordered s...
12,504
method name keys values items get get use explanation returns the keys of the dictionary in dict_keys object my_dict values(returns the values of the dictionary in dict_values object my_dict items(returns the key-value pairs in dict_items object my_dict get(kreturns the value associated with knone otherwise my_dict get...
12,505
user_name input('please enter your name'now whatever the user types after the prompt will be stored in the user_name variable using the input functionwe can easily write instructions that will prompt the user to enter data and then incorporate that data into further processing for examplein the following two statements...
12,506
character output format , integer unsigned integer floating point as ddddd floating point as ddddde+/-xx floating point as ddddde+/-xx use % for exponents less than - or greater than + otherwise us % single character stringor any python data object that can be converted to string by using the str function insert litera...
12,507
modifier example number % %- %+ % % (name%(name) description put the value in field width of put the value in field characters wideleft-justified put the value in field characters wideright-justified put the value in field characters widefill in with leading zeros put the value in field characters wide with characters ...
12,508
helloworld helloworld helloworld prints out the phrase "helloworldfive times the condition on the while statement is evaluated at the start of each repetition if the condition is truethe body of the statement will execute it is easy to see the structure of python while statement due to the mandatory indentation pattern...
12,509
will perform the print function five times the range function will return range object representing the sequence and each value will be assigned to the variable item this value is then squared and printed the other very useful version of this iteration structure is used to process each character of string the following...
12,510
print(' 'python also has single way selection constructthe if statement with this statementif the condition is truean action is performed in the case where the condition is falseprocessing simply continues on to the next statement after the if for examplethe following fragment will first check to see if the value of va...
12,511
[' '' '' '' '' '' '' '' 'self check test your understanding of what we have covered so far by trying the following two exercises use the code belowseen earlier in this subsection word_list ['cat','dog','rabbit'letter_list for a_word in word_listfor a_letter in a_wordletter_list append(a_letterprint(letter_list modify t...
12,512
most of the timebeginning programmers simply think of exceptions as fatal runtime errors that cause the end of execution howevermost programming languages provide way to deal with these errors that will allow the programmer to have some type of intervention if they so choose in additionprogrammers can create their own ...
12,513
the programmer if a_number raise runtimeerror("you can' use negative number"elseprint(math sqrt(a_number)traceback (most recent call last)file ""line in raise runtimeerror("you can' use negative number"runtimeerroryou can' use negative number there are many kinds of exceptions that can be raised in addition to the runt...
12,514
takes value and repeatedly guesses the square root by making each new_guess the old_guess in the subsequent iteration the initial guess used here is listing shows function definition that accepts value and returns the square root of after making guesses againthe details of newton' method are hidden inside the function ...
12,515
class of "hill climbingalgorithmsthat is we only keep the result if it is better than the previous one object-oriented programming in pythondefining classes we stated earlier that python is an object-oriented programming language so farwe have used number of built-in classes to show examples of data and control structu...
12,516
figure an instance of the fraction class underscores before and after initand is shown in listing listing fraction class and its constructor class fractiondef __init__(self,top,bottom)self num top self den bottom notice that the formal parameter list contains three items (selftopbottomself is special parameter that wil...
12,517
the fraction objectmy_fdoes not know how to respond to this request to print the print function requires that the object convert itself into string so that the string can be written to the output the only choice my_f has is to show the actual reference that is stored in the variable (the address itselfthis is not what ...
12,518
' / str(my_f' / we can override many other methods for our new fraction class some of the most important of these are the basic arithmetic operations we would like to be able to create two fraction objects and then add them together using the standard "+notation at this pointif we try to add two fractionswe get the fol...
12,519
return fraction(new_numnew_denf fraction( fraction( print( / the addition method works as we desirebut one thing could be better note that is the correct result but that it is not in the "lowest termsrepresentation the best representation would be in order to be sure that our results are always in the lowest termswe ne...
12,520
figure an instance of the fraction class with two methods fraction( fraction( print( / our fraction object now has two very useful methods and looks like figure an additional group of methods that we need to include in our example fraction class will allow two fractions to compare themselves to one another assume we ha...
12,521
figure shallow equality versus deep equality introduction
12,522
gcd function def gcd(mn)while ! old_m old_n old_n old_m old_n return fraction class implementsaddition and equality to domultiplicationdivisionsubtraction and comparison operators (class fractiondef __init__(selftopbottom)self num top self den bottom def __str__(self)return str(self num"/str(self dendef show(self)print...
12,523
summary computer science is the study of problem solving computer science uses abstraction as tool for representing both processes and data abstract data types allow programmers to manage the complexity of problem domain by hiding the details of the data python is powerfulyet easy-to-useobject-oriented language liststu...
12,524
modify the constructor for the fraction class so that it checks to make sure that the numerator and denominator are both integers if either is not an integer the constructor should raise an exception in the definition of fractions we assumed that negative fractions have negative numerator and positive denominator using...
12,525
introduction
12,526
two algorithm analysis objectives to understand why algorithm analysis is important to be able to use "big-oto describe execution time to understand the "big-oexecution time of common operations on python lists and dictionaries to understand how the implementation of python data impacts algorithm analysis to understand...
12,527
the_sum the_sum return the_sum print(sum_of_n( )now look at the function foo below at first glance it may look strangebut upon further inspection you can see that this function is essentially doing the same thing as the previous one the reason this is not obvious is poor coding we did not use good identifier names to a...
12,528
in seconds since some arbitrary starting point by calling this function twiceat the beginning and at the endand then computing the differencewe can get an exact number of seconds (fractions in most casesfor execution import time def sum_of_n_ ( )start time time(the_sum for in range( + )the_sum the_sum end time time(ret...
12,529
to compute the sum of the first integers without iterating def sum_of_n_ ( )return ( ( ) print(sum_of_n_ ( )we do the same benchmark measurement for sum_of_n_ using five different values for ( and )we get the following resultssum is required seconds sum is required seconds sum is required seconds sum is required second...
12,530
where ( the parameter is often referred to as the "size of the problem,and we can read this as " (nis the time it takes to solve problem of size nnamely steps in the summation functions given aboveit makes sense to use the number of terms in the summation to denote the size of the problem we can then say that the sum o...
12,531
(nname constant log logarithmic linear log log linear quadratic cubic exponential table common functions for big- figure plot of common big- functions the functions are not very well defined with respect to one another it is hard to tell which is dominant howeveras growsthere is definite relationship and it is easy to ...
12,532
figure comparing (nwith common big- functions for in range( ) the number of assignment operations is the sum of four terms the first term is the constant representing the three assignment statements at the start of the fragment the second term is since there are three statements that are performed times due to the nest...
12,533
an anagram detection example good example problem for showing algorithms with different orders of magnitude is the classic anagram detection problem for strings one string is an anagram of another if the second is simply rearrangement of the first for example'heartand 'earthare anagrams the strings 'pythonand 'typhonar...
12,534
the integers from to we stated earlier that this can be written as ii= ( as gets largethe term will dominate the term and the can be ignored thereforethis solution is ( solution sort and compare another solution to the anagram problem will make use of the fact that even though and are differentthey are anagrams only if...
12,535
characters from and then see if occurs howeverthere is difficulty with this approach when generating all possible strings from there are possible first charactersn- possible characters for the second positionn for the thirdand so on the total number of candidate strings is ( ( which is nalthough some of the strings may...
12,536
characters in the strings adding it all up gives us ( steps that is (nwe have found linear order of magnitude algorithm for solving this problem before leaving this examplewe need to say something about space requirements although the last solution was able to run in linear timeit could only do so by using additional s...
12,537
( ( (log ( performance of python data structures now that you have general idea of big- notation and the differences between the different functionsour goal in this section is to tell you about the big- performance for the operations on python lists and dictionaries we will then show you some timing experiments that il...
12,538
for in range( ) [idef test () [for in range( ) append(idef test () [ for in range( )def test () list(range( )to capture the time it takes for each of our functions to execute we will use python' timeit module the timeit module is designed to allow python developers to make cross-platform timing measurements by running ...
12,539
in the experiment above the statement that we are timing is the function call to test ()test ()and so on the setup statement may look very strange to youso let us consider it in more detail you are probably very familiar with the fromimport statementbut this is usually used at the beginning of python program file in th...
12,540
operation indexx[index assignment append pop(pop(iinsert( ,itemdel operator iteration contains (inget slice [ :ydel slice set slice reverse concatenate sort multiply big- efficiency ( ( ( ( (no(no(no(no(no(ko(no( ko(no(ko( log no(nktable big- efficiency of python list operators times it is also important to point out t...
12,541
figure comparing the performance of pop and pop( pz pop_zero timeit(number= print("% % %(pz,pt)figure shows the results of our experiment you can see that as the list gets longer and longer the time it takes to pop( also increases while the time for pop stays very flat this is exactly what we would expect to see for (n...
12,542
operation big- efficiency copy (nget item ( set item ( delete item ( contains (ino( iteration (ntable big- efficiency of python dictionary operations is summarized in table one important side note on dictionary performance is that the efficiencies we provide in the table are for average performance in some rare cases t...
12,543
figure comparing the in operator for python lists and dictionaries time for the contains operator on dictionary is constant even as the dictionary size grows in fact for dictionary size of the contains operation took milliseconds and for the dictionary size of it also took milliseconds since python is an evolving langu...
12,544
'xin my_dict del my_dict[' ' my_dict[' '= my_dict[' 'my_dict[' ' all of the above are ( summary algorithm analysis is an implementation-independent way of measuring an algorithm big- notation allows algorithms to be classified by their dominant process with respect to the size of the problem key terms average case chec...
12,545
for in range( )for in range( )for in range( ) give the big- performance of the following code fragmenti while / give the big- performance of the following code fragmentfor in range( ) for in range( ) for in range( ) programming exercises devise an experiment to verify that the list index operator is ( devise an experim...
12,546
three basic data structures objectives to understand the abstract data types stackqueuedequeand list to be able to implement the adts stackqueueand deque using python lists to understand the performance of the implementations of basic linear data structures to understand prefixinfixand postfix expression formats to use...
12,547
figure stack of books new items to be added at only one end some structures might allow items to be removed from either end these variations give rise to some of the most useful data structures in computer science they appear in many algorithms and can be used to solve variety of important problems stacks what is stack...
12,548
figure stack of primitive python objects figure the reversal property of stacks stacks
12,549
stack operation stack contents return value is_empty( push( push('dog' peek( push(trues size( is_empty( push( pop( pop( size([[ [ ,'dog'[ ,'dog'[ ,'dog',true[ ,'dog',true[ ,'dog',true[ ,'dog',true, [ ,'dog',true[ ,'dog'[ ,'dog'true 'dog false true table sample stack operations you use your computer for exampleevery web...
12,550
implementing stack in python now that we have clearly defined the stack as an abstract data type we will turn our attention to using python to implement the stack recall that when we give an abstract data type physical implementation we refer to the implementation as data structure as we described in in pythonas in any...
12,551
print( peek() push(trueprint( size()print( is_empty() push( print( pop()print( pop()print( size()it is important to note that we could have chosen to implement the stack using list where the top is at the beginning instead of at the end in this casethe previous pop and append methods would no longer work and we would h...
12,552
self check given the following sequence of stack operationswhat is the top item on the stack when the sequence is completem stack( push(' ' push(' ' pop( push(' ' peek( ' ' ' the stack is empty given the following sequence of stack operationswhat is the top item on the stack when the sequence is completem stack( push('...
12,553
figure matching parentheses this defines function called square that will return the square of its argument lisp is notorious for using lots and lots of parentheses in both of these examplesparentheses must appear in balanced fashion balanced parentheses means that each opening symbol has corresponding closing symbol a...
12,554
erly at the end of the stringwhen all symbols have been processedthe stack should be empty import stack #import the stack class as previously defined def par_checker(symbol_string) stack(balanced true index while index len(symbol_stringand balancedsymbol symbol_string[indexif symbol ="(" push(symbolelseif is_empty()bal...
12,555
are properly balanced in that not only does each opening symbol have corresponding closing symbolbut the types of symbols match as well compare those with the following strings that are not balancedthe simple parentheses checker from the previous section can easily be extended to handle these new types of symbols recal...
12,556
if balanced and is_empty()return true elsereturn false def matches(openclose)opens "([{closes ")]}return opens index(open=closes index(close print(par_checker('{{([][])}()}')print(par_checker('[{()]')these two examples show that stacks are very important data structures for the processing of language constructs in comp...
12,557
figure decimal-to-binary conversion creates an empty string the binary digits are popped from the stack one at time and appended to the right-hand end of the string the binary string is then returned import stack as previously defined def divide_by_ (dec_number)rem_stack stack( while dec_number rem dec_number rem_stack...
12,558
numbers need maximum of digitsso the typical digit characters and work fine the problem comes when we go beyond base we can no longer simply use the remaindersas they are themselves represented as two-digit decimal numbers instead we need to create set of digits that can be used to represent those remainders beyond imp...
12,559
in the expression this type of notation is referred to as infix since the operator is in between the two operands that it is working on consider another infix examplea the operators and still appear between the operandsbut there is problem which operands do they work ondoes the work on and or does the take and cthe exp...
12,560
infix expression + + * prefix expression +ab + bc postfix expression ababc table examples of infixprefixand postfix infix expression ( bc prefix expression abc postfix expression ab ctable an expression with parentheses + was written in prefixthe addition operator was simply moved before the operands+ab the result of t...
12,561
figure moving operators to the right for postfix notationfigure moving operators to the left for prefix notationmultiplication symbol to that position and remove the matching left parenthesisgiving us bc*we would in effect have converted the subexpression to postfix notation if the addition operator were also moved to ...
12,562
of the operators in the original expression is reversed in the resulting postfix expression as we process the expressionthe operators have to be saved somewhere since their corresponding right operands are not seen yet alsothe order of these saved operators may need to be reversed due to their precedence this is the ca...
12,563
figure converting to postfix notationinfix expression the stack is popped twiceremoving both operators and placing as the last operator in the postfix expression in order to code the algorithm in pythonwe will use dictionary called prec to hold the precedence values for the operators this dictionary will map each opera...
12,564
while top_token !'('postfix_list append(top_tokentop_token op_stack pop(elsewhile (not op_stack is_empty()and (prec[op_stack peek()>prec[token])postfix_list append(op_stack pop()op_stack push(token while not op_stack is_empty()postfix_list append(op_stack pop()return join(postfix_list print(infix_to_postfix(" ")print(i...
12,565
figure sack contents during evaluationfigure more complex example of evaluationfigure shows slightly more complex example + +there are two things to note in this example firstthe stack size growsshrinksand then grows again as the subexpressions are evaluated secondthe division operation needs to be handled carefully re...
12,566
when the input expression has been completely processedthe result is on the stack pop the operand_stack and return the value the complete function for the evaluation of postfix expressions is shown below to assist with the arithmetica helper function do_math is defined that will take two operands and an operator and th...
12,567
figure queue of python data objects queues we now turn our attention to another linear data structure this one is called queue like stacksqueues are relatively simple and yet can be used to solve wide range of important problems what is queuea queue is an ordered collection of items where the addition of new items happ...
12,568
queue operation queue contents return value is_empty( enqueue( enqueue('dog' enqueue(trueq size( is_empty( enqueue( dequeue( dequeue( size([[ ['dog', [true,'dog', [true,'dog', [true,'dog', [ ,true,'dog', [ ,true,'dog'[ ,true[ ,truetrue false 'dog table example queue operations the queue abstract data type the queue abs...
12,569
can be used to remove the front element (the last element of the listrecall that this also means that enqueue will be (nand dequeue will be ( completed implementation of queue adt class queuedef __init__(self)self items [def is_empty(self)return self items =[def enqueue(selfitem)self items insert( ,itemdef dequeue(self...
12,570
figure six person game of hot potatothis game is modern-day equivalent of the famous josephus problem based on legend about the famous first-century historian flavius josephusthe story is told that in the jewish revolt against romejosephus and of his comrades held out against the romans in cave with defeat imminentthey...
12,571
figure queue implementation of hot potatowhile sim_queue size( for in range(num)sim_queue enqueue(sim_queue dequeue()sim_queue dequeue(return sim_queue dequeue(print(hot_potato(["bill""david""susan""jane""kent""brad"] )note that in this example the value of the counting constant is greater than the number of names in t...
12,572
figure computer science laboratory printing queuewe could decide by building simulation that models the laboratory we will need to construct representations for studentsprinting tasksand the printer (figure as students submit printing taskswe will add them to waiting lista queue of print tasks attached to the printer w...
12,573
for each second (current_second)does new print task get createdif soadd it to the queue with the current_second as the timestamp if the printer is not busy and if task is waitingremove the next task from the print queue and assign it to the printer subtract the timestamp from the current_second to compute the waiting t...
12,574
def start_next(self,new_task)self current_task new_task self time_remaining new_task get_pages( self page_rate the task class will represent single printing task when the task is createda random number generator will provide length from to pages we have chosen to use the randrange function from the random module import...
12,575
import task as previously defined import random def simulation(num_secondspages_per_minute)lab_printer printer(pages_per_minuteprint_queue queue(waiting_times [for current_second in range(num_seconds)if new_print_task()task task(current_secondprint_queue enqueue(taskif (not lab_printer busy()and (not print_queue is_emp...
12,576
average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining average wait secs tasks remaining after running our trials we can see that the mea...
12,577
self current_task none def busy(self)if self current_task !nonereturn true elsereturn false def start_next(selfnew_task)self current_task new_task self time_remaining new_task get_pages( /self page_rate class taskdef __init__(selftime)self timestamp time self pages random randrange( def get_stamp(self)return self times...
12,578
num random randrange( if num = return true elsereturn false for in range( )simulation( discussion we were trying to answer question about whether the current printer could handle the task load if it were set to print with better quality but slower page rate the approach we took was to write simulation that modeled the ...
12,579
figure deque of python data objects queue deques we will conclude this introduction to basic data structures by looking at another variation on the theme of linear collections howeverunlike stack and queuethe deque (pronounced "deck"has very few restrictions alsobe careful that you do not confuse the spelling of "deque...
12,580
deque operation deque contents return value is_empty( add_rear( add_rear('dog' add_front('cat' add_front(trued size( is_empty( add_rear( remove_rear( remove_front([[ ['dog', ,['dog', ,'cat'['dog', ,'cat',true['dog', ,'cat',true['dog', ,'cat',true[ ,'dog', ,'cat',true['dog', ,'cat',true['dog', ,'cat'true false true tabl...
12,581
self items append(itemdef add_rear(selfitem)self items insert( ,itemdef remove_front(self)return self items pop(def remove_rear(self)return self items pop( def size(self)return len(self itemsin remove_front we use the pop method to remove the last element from the list howeverin remove_rearthe pop( method must remove t...
12,582
figure dequechar_deque add_rear(chstill_equal true while char_deque size( and still_equalfirst char_deque remove_front(last char_deque remove_rear(if first !laststill_equal false return still_equal print(pal_checker("lsdkjfskf")print(pal_checker("radar") lists throughout the discussion of basic data structureswe have u...
12,583
common way of showing the list structure of coursepython would show this list as [ the unordered list abstract data type the structure of an unordered listas described aboveis collection of items where each item holds relative position with respect to the others some possible unordered list operations are given below l...
12,584
figure items not constrained in their physical placement figure relative positions maintained by explicit links the location of the next item (see figure then the relative position of each item can be expressed by simply following the link from one item to the next it is important to note that the location of the first...
12,585
figure node object contains the item and reference to the next node figure typical representation for node def get_next(self)return self next def set_data(selfnew_data)self data newdata def set_next(selfnew_next)self next new_next we create node objects in the usual way temp node( temp get_data( the special python refe...
12,586
figure an empty list figure linked list of integers def __init__(self)self head none initially when we construct listthere are no items the assignment statement mylist unorderedlist(creates the linked list representation shown in figure as we discussed in the node classthe special reference none will again be used to s...
12,587
figure adding new node is two-step process recall that the linked list structure provides us with only one entry pointthe head of the list all of the other nodes can only be reached by accessing the first node and then following next links this means that the easiest place to add the new node is right at the heador beg...
12,588
figure result of reversing the order of the two steps figure traversing the linked list from the head to the end node to do this we use an external reference that starts at the first node in the list as we visit each nodewe move the reference to the next node by "traversingthe next reference to implement the size metho...
12,589
figure successful search for the value the code below shows the implementation for the search method as in the size methodthe traversal is initialized to start at the head of the list (line we also use boolean variable called found to remember whether we have located the item we are searching for since we have not foun...
12,590
item with some marker that suggests that the item is no longer present the problem with this approach is the number of nodes will no longer match the number of items it would be much better to remove the item by removing the entire node in order to remove the node containing the itemwe need to modify the link in the pr...
12,591
figure initial values for the previous and current references figure previous and current move down the list basic data structures
12,592
figure removing an item from the middle of the list figure removing the first node from the list needs to be modified in order to complete the remove in this caseit is not previous but rather the head of the list that needs to be changed (see figure line allows us to check whether we are dealing with the special case d...
12,593
figure an ordered linked list the ordered list abstract data type we will now consider type of list known as an ordered list for exampleif the list of integers shown above were an ordered list (ascending order)then it could be written as and since is the smallest itemit occupies the first position in the list likewises...
12,594
figure searching an ordered linked list to implement the orderedlist classwe will use the same technique as seen previously with unordered lists once againan empty list will be denoted by head reference to none class orderedlistdef __init__(self)self head none as we consider the operations for the ordered listwe should...
12,595
figure adding an item to an ordered linked list if current get_data(=itemfound true elseif current get_data(itemstop true elsecurrent current get_next( return found the most significant method modification will take place in add recall that for unordered liststhe add method could simply place new node at the head of th...
12,596
while current !none and not stopif current get_data(itemstop true elseprevious current current current get_next( temp node(itemif previous =nonetemp set_next(self headself head temp elsetemp set_next(currentprevious set_next(tempanalysis of linked lists to analyze the complexity of the linked list operationswe need to ...
12,597
queues can assist in the construction of timing simulations simulations use random number generators to create real-life situation and allow us to answer "what iftypes of questions deques are data structures that allow hybrid behavior like that of stacks and queues the fundamental operations for deque are add_frontadd_...
12,598
the alternative implementation of the queue adt is to use list such that the rear of the queue is at the end of the list what would this mean for big- performance what is the result of carrying out both steps of the linked list add method in reverse orderwhat kind of reference resultswhat types of problems may result e...
12,599
modify the hot potato simulation to allow for randomly chosen counting value so that each pass is not predictable from the previous one implement radix sorting machine radix sort for base integers is mechanical sorting technique that utilizes collection of binsone main bin and digit bins each bin acts like queue and ma...