id
int64
0
25.6k
text
stringlengths
0
4.59k
9,200
indexing we will often want to pick out individual characters from string python uses square brackets to do this the table below gives some examples of indexing the string ='pythonstatement result description [ first character of [ second character of [- last character of [- second-to-last character of the first character of is [ ]not [ remember that in programmingcounting usually starts at not negative indices count backwards from the end of the string common error suppose ='pythonand we try to do [ there are only six characters in the string and python will raise the following error messageindexerrorstring index out of range you will see this message again remember that it happens when you try to read past the end of string slices slice is used to pick out part of string it behaves like combination of indexing and the range function below we have some examples with the string ='abcdefghijindexletters code result description [ : cde characters at indices : abcde first five characters [ fghij characters from index to the end [- ij last two characters sabcdefghij entire string [ : : bdf characters from index to by twos :- jihgfedcba negative step reverses the string
9,201
strings the basic structure is string name[starting location ending location+ slices have the same quirk as the range function in that they do not include the ending location for instancein the example aboves[ : gives the characters in indices and but not the character in index we can leave either the starting or ending locations blank if we leave the starting location blankit defaults to the start of the string so [: gives the first five characters of if we leave the ending location blankit defaults to the end of the string so [ :will give all the characters from index to the end if we use negative indiceswe can get the ending characters of the string for instances[- :gives the last two characters there is an optional third argumentjust like in the range statementthat can specify the step for examples[ : : steps through the string by twosselecting the characters at indices and (but not because of the aforementioned quirkthe most useful step is - which steps backwards through the stringreversing the order of the characters changing individual characters of string suppose we have string called and we want to change the character at index of to 'xit is tempting to try [ ]=' 'but that unfortunately will not work python strings are immutablewhich means we can' modify any part of them there is more on why this is in section if we want to change character of swe have to instead build new string from and reassign it to here is code that will change the character at index to ' ' [: ' [ :the idea of this is we take all the characters up to index then xand then all of the characters after index looping very often we will want to scan through string one character at time for loop like the one below can be used to do that it loops through string called sprinting the stringcharacter by charactereach on separate linefor in range(len( ))print ( [ ]in the range statement we have len(sthat returns how long is soif were characters longthis would be like having range( and the loop variable would run from to this means that [iwill run through the characters of this way of looping is useful if we need to keep track of our location in the string during the loop if we don' need to keep track of our locationthen there is simpler type of loop we can use
9,202
for in sprint(cthis loop will step through scharacter by characterwith holding the current character you can almost read this like an english sentence"for every character in sprint that character string methods strings come with ton of methodsfunctions that return information about the string or return new string that is modified version of the original here are some of the most useful onesmethod description lower(returns string with every letter of the original in lowercase upper(returns string with every letter of the original in uppercase replace( ,yreturns string with every occurrence of replaced by count(xcounts the number of occurrences of in the string index(xreturns the location of the first occurrence of isalpha(returns true if every character of the string is letter important note one very important note about lowerupperand replace is that they do not change the original string if you want to change stringsto all lowercaseit is not enough to just use lower(you need to do the followings lower(short examples here are some examples of string methods in actionstatement description print( count(')prints the number of spaces in the string upper(changes the string to all caps replace('hi','hello'replaces each 'hiin with 'helloprint( index(' ')prints location of the first 'ain isalpha the isalpha method is used to tell if character is letter or not it returns true if the character is letter and false otherwise when used with an entire stringit will only return true if every character of the string is letter the values true and false are called booleans and are covered in section for nowthoughjust remember that you can use isalpha in if conditions here is simple examples input'enter string '
9,203
strings if [ isalpha()print'your string starts with letter 'if not isalpha()print'your string contains non-letter ' note about index if you try to find the index of something that is not in stringpython will raise an error for instanceif ='abcand you try index(' ')you will get an error one way around this is to check firstlike belowif ' in slocation index' 'other string methods there are many more string methods for instancethere are methods isdigit and isalnumwhich are analogous to isalpha some other useful methods we will learn about later are join and split to see list of all the string methodstype dir(strinto the python shell if you do thisyou will see bunch of names that start with __ you can ignore them to read python' documentation for one of the methodssay the isdigit methodtype help(str isdigit escape characters the backslash\is used to get certain special characterscalled escape charactersinto your string there are variety of escape charactersand here are the most useful ones\ the newline character it is used to advance to the next line here is an exampleprint'hi\ \nthere'hi there\for inserting apostrophes into strings say you have the following strings ' can ' go this will produce an error because the apostrophe will actually end the string you can use \to get around thiss ' can\' go another option is to use double quotes for the string" can ' go\analogous to \
9,204
\ this is used to get the backslash itself for examplefilename ' :\\programs\\file py \ the tab character examples example an easy way to print blank line is print(howeverif we want to print ten blank linesa quick way to do that is the followingprint'\ '* note that we get one of the ten lines from the print function itself example write program that asks the user for string and prints out the location of each 'ain the string input'enter some text'for in range(len( ))if [ ]=' 'print(iwe use loop to scan through the string one character at time the loop variable keeps track of our location in the stringand [igives the character at that location thusthe third line checks each character to see if it is an ' 'and if soit will print out ithe location of that 'aexample write program that asks the user for string and creates new string that doubles each character of the original string for instanceif the user enters hellothe output should be hheelllloo input'enter some text'doubled_s 'for in sdoubled_s doubled_s * here we can use the second type of loop from section the variable will run through the characters of we use the repetition operator*to double each character we build up the string in the way described at the end of section example write program that asks user for their name and prints it in the following funny patterne el elv elvi elvis
9,205
strings we will require loop because we have to repeatedly print sections of the stringand to print the sections of the stringwe will use slicename input'enter your name'for in range(len(name))print(name[: + ]end'the one trick is to use the loop variable in the slice since the number of characters we need to print is changingwe need variable amount in the slice this is reminiscent of the triangle program from section we want to print one character of the name the first time through the looptwo characters the second timeetc the loop variableistarts at the first time through the loopthen increases to the second time through the loopetc thus we use name[: + to print the first + characters of the name finallyto get all the slices to print on the same linewe use the print function' optional argument end='example write program that removes all capitalization and common punctuation from string lower(for in ';:-?!()\'' replace( ''the way this works is for every character in the string of punctuationwe replace every occurrence of it in with the empty string'one technical note herewe need the character in string as described in the previous sectionwe get it into the string by using the escape character \example write program thatgiven string that contains decimal numberprints out the decimal part of the number for instanceif given the program should print out input'enter your decimal number'print( [ index'):]the key here is the index method will find where the decimal point is the decimal part of the number starts there and runs to the end of the stringso we use slice that starts at index('here is anothermore mathematical wayto do thisfrom math import floor num eval(input'enter your decimal number'print(num floor(num)one difference between the two methods is the first produces stringwhereas the second produces number
9,206
example simple and very old method of sending secret messages is the substitution cipher basicallyeach letter of the alphabet gets replaced by another letter of the alphabetsay every gets replaced with an xand every gets replaced by zetc write program to implement this alphabet 'abcdefghijklmnopqrstuvwxyz key 'xznlwebgjhqdyvtkfuompciasr secret_message input'enter your message'secret_message secret_message lower(for in secret_messageif isalpha()print(key[alphabet index( )],end''elseprint(cend''the string key is random reordering of the alphabet the only tricky part of the program is the for loop what it does is go through the message one character at timeandfor every letter it findsit replaces it with the corresponding letter from the key this is accomplished by using the index method to find the position in the alphabet of the current letter and replacing that letter with the letter from the key at that position all non-letter characters are copied as is the program uses the isalpha method to tell whether the current character is letter or not the code to decipher message is nearly the same just change key[alphabet index( )to alphabet[key index( )section provides different approach to the substitution cipher exercises write program that asks the user to enter string the program should then print the following(athe total number of characters in the string (bthe string repeated times (cthe first character of the string (remember that string indices start at (dthe first three characters of the string (ethe last three characters of the string (fthe string backwards (gthe seventh character of the string if the string is long enough and message otherwise (hthe string with its first and last characters removed (ithe string in all caps (jthe string with every replaced with an
9,207
strings (kthe string with every letter replaced by space simple way to estimate the number of words in string is to count the number of spaces in the string write program that asks the user for string and returns an estimate of how many words are in the string people often forget closing parentheses when entering formulas write program that asks the user to enter formula and prints out whether the formula has the same number of opening and closing parentheses write program that asks the user to enter word and prints out whether that word contains any vowels write program that asks the user to enter string the program should create new string called new_string from the user' string such that the second character is changed to an asterisk and three exclamation points are attached to the end of the string finallyprint new_string typical output is shown belowenter your stringqbert *ert!! write program that asks the user to enter string and then converts to lowercaseremoves all the periods and commas from sand prints the resulting string write program that asks the user to enter word and determines whether the word is palindrome or not palindrome is word that reads the same backwards as forwards at certain schoolstudent email addresses end with @student college eduwhile professor email addresses end with @prof college edu write program that first asks the user how many email addresses they will be enteringand then has the user enter those addresses after all the email addresses are enteredthe program should print out message indicating either that all the addresses are student addresses or that there were some professor addresses entered ask the user for number and then print the followingwhere the pattern ends at the number that the user enters write program that asks the user to enter stringthen prints out each letter of the string doubled and on separate line for instanceif the user entered heythe output would be hh ee yy
9,208
write program that asks the user to enter word that contains the letter the program should then print the following two lineson the first line should be the part of the string up to and including the first aand on the second line should be the rest of the string sample output is shown belowenter wordbuffalo buffa lo write program that asks the user to enter word and then capitalizes every other letter of that word so if the user enters rhinocerosthe program should print rhinoceros write program that asks the user to enter two strings of the same length the program should then check to see if the strings are of the same length if they are notthe program should print an appropriate message and exit if they are of the same lengththe program should alternate the characters of the two strings for exampleif the user enters abcde and abcde the program should print out aabbccddee write program that asks the user to enter their name in lowercase and then capitalizes the first letter of each word of their name when was kidwe used to play this game called mad libs the way it worked was friend would ask me for some words and then insert those words into story at specific places and read the story the story would often turn out to be pretty funny with the words had given since had no idea what the story was about the words were usually from specific categorylike placean animaletc for this problem you will write mad libs program firstyou should make up story and leave out some words of the story your program should ask the user to enter some words and tell them what types of words to enter then print the full story along with the inserted words here is small examplebut you should use your own (longerexampleenter college classcalculus enter an adjectivehappy enter an activityplay basketball calculus class was really happy today we learned how to play basketball today in class can' wait for tomorrow' class companies often try to personalize their offers to make them more attractive one simple way to do this is just to insert the person' name at various places in the offer of coursecompanies don' manually type in every person' nameeverything is computer-generated write program that asks the user for their name and then generates an offer like the one below for simplicity' sakeyou may assume that the person' first and last names are one word each enter namegeorge washington
9,209
strings dear george washingtoni am pleased to offer you our new platinum plus rewards card at special introductory apr of georgean offer like this does not come along every dayso urge you to call now toll-free at - we cannot offer such low rate for longgeorgeso call right away write program that generates the -line block of letters partially shown below use loop containing one or two print statements abcdefghijklmnopqrstuvwxyz bcdefghijklmnopqrstuvwxyza cdefghijklmnopqrstuvwxyzab yzabcdefghijklmnopqrstuvwx zabcdefghijklmnopqrstuvwxy the goal of this exercise is to see if you can mimic the behavior of the in operator and the count and index methods using only variablesfor loopsand if statements (awithout using the in operatorwrite program that asks the user for string and letter and prints out whether or not the letter appears in the string (bwithout using the count methodwrite program that asks the user for string and letter and counts how many occurrences there are of the letter in the string (cwithout using the index methodwrite program that asks the user for string and letter and prints out the index of the first occurrence of the letter in the string if the letter is not in the stringthe program should say so write program that asks the user for large integer and inserts commas into it according to the standard american convention for commas in large numbers for instanceif the user enters the output should be , , write program that converts time from one time zone to another the user enters the time in the usual american waysuch as : pm or : am the first time zone the user enters is that of the original time and the second is the desired time zone the possible time zones are easterncentralmountainor pacific time : pm starting zonepacific ending zoneeastern : am an anagram of word is word that is created by rearranging the letters of the original for instancetwo anagrams of idle are deli and lied finding anagrams that are real words is beyond our reach until insteadwrite program that asks the user for string and returns random anagram of the string--in other wordsa random rearrangement of the letters of that string
9,210
simple way of encrypting message is to rearrange its characters one way to rearrange the characters is to pick out the characters at even indicesput them first in the encrypted stringand follow them by the odd characters for examplethe string message would be encrypted as msaeesg because the even characters are msae (at indices and and the odd characters are esg (at indices and (awrite program that asks the user for string and uses this method to encrypt the string (bwrite program that decrypts string that was encrypted with this method more general version of the above technique is the rail fence cipherwhere instead of breaking things into evens and oddsthey are broken up by threesfours or something larger for instancein the case of threesthe string secret message would be broken into three groups the first group is sr sgthe characters at indices and the second group is eemsethe characters at indices and the last group is cteathe characters at indices and the encrypted message is sr sgeemsectea (awrite program the asks the user for string and uses the rail fence cipher in the threes case to encrypt the string (bwrite decryption program for the threes case (cwrite program that asks the user for stringand an integer determining whether to break things up by threesfoursor whatever encrypt the string using the rail-fence cipher (dwrite decryption program for the general case in calculusthe derivative of is the derivative of is the derivative of is this pattern continues write program that asks the user for input like ^ or ^ and prints the derivative for exampleif the user enters ^ the program should print out ^ in algebraic expressionsthe symbol for multiplication is often left outas in + or ( + computers prefer those expressions to include the multiplication symbollike * + * or *( + write program that asks the user for an algebraic expression and then inserts multiplication symbols where appropriate
9,211
strings
9,212
lists say we need to get thirty test scores from user and do something with themlike put them in order we could create thirty variablesscore score score but that would be very tedious to then put the scores in order would be extremely difficult the solution is to use lists basics creating lists here is simple listl [ , , use square brackets to indicate the start and end of the listand separate the items by commas the empty list the empty list is [it is the list equivalent of or 'long lists if you have long list to enteryou can split it across several lineslike belownums [ input we can use eval(input()to allow the user to enter list here is an examplel eval(input'enter list')print'the first element is ' [ ]enter list[ , , the first element is
9,213
lists printing lists you can use the print function to print the entire contents of list [ , , print( [ data types valid listlists can contain all kinds of thingseven other lists for examplethe following is [ 'abc '[ , , ] similarities to strings there are number of things which work the same way for lists as for strings len -the number of items in is given by len(lin -the in operator tells you if list contains something here are some examplesif in lprint'your list contains the number 'if not in lprint'your list has no zeroes 'indexing and slicing -these work exactly as with strings for examplel[ is the first item of the list and [: gives the first three items index and count -these methods work the same as they do for strings and -the operator adds one list to the end of another the operator repeats list here are some examplesexpression result [ , ]+[ , , [ , , , , [ , ]* [ , , , , , [ ]* [ , , , , the last example is particularly useful for quickly creating list of zeroes looping -the same two types of loops that work for strings also work for lists both of the following examples print out the items of listone-by-oneon separate lines for in range(len( ))print( [ ]for item in lprint(itemthe left loop is useful for problems where you need to use the loop variable to keep track of where you are in the loop if that is not neededthen use the right loopas it is little simpler
9,214
built-in functions there are several built-in functions that operate on lists here are some useful onesfunction description len returns the number of items in the list sum returns the sum of the items in the list min returns the minimum of the items in the list max returns the maximum of the items in the list for examplethe following computes the average of the values in list laverage sum( )/len( list methods here are some list methodsmethod description append(xadds to the end of the list sort(sorts the list count(xreturns the number of times occurs in the list index(xreturns the location of the first occurrence of reverse(reverses the list remove(xremoves first occurrence of from the list pop(premoves the item at index and returns its value insert( ,xinserts at index of the list important note there is big difference between list methods and string methodsstring methods do not change the original stringbut list methods do change the original list to sort list ljust use sort(and not = sort(in factthe latter will not work at all wrong right replace(' ',' ' replace(' ',' ' sort( sort(other list methods there are few others list methods type help(listin the python shell to see some documentation for them
9,215
lists miscellaneous making copies of lists making copies of lists is little tricky due to the way python handles lists say we have list and we want to make copy of the list and call it the expression = will not work for reasons covered in section for nowdo the following in place of =lm [:changing lists changing specific item in list is easier than with strings to change the value in location of to we simply say [ ]= if we want to insert the value into location without overwriting what is currently therewe can use the insert method to delete an entry from listwe can use the del operator some examples are shown below assume =[ , , for each operation operation new description [ ] [ , replace item at index with insert( , [ , insert at index without replacing del [ [ , delete second item del [: [ delete first two items examples example write program that generates list of random numbers between and from random import randint [for in range( ) append(randint( , )we use the append method to build up the list one item at time starting with the empty list[an alternative to append is to use the followingl [randint( , )example replace each element in list with its square for in range(len( )) [il[ ]** example count how many items in list are greater than
9,216
count for item in lif item> count=count+ example given list that contains numbers between and create new list whose first element is how many ones are in lwhose second element is how many twos are in letc frequencies [for in range( , )frequences append( count( )the key is the list method count that tells how many times something occurs in list example write program that prints out the two largest and two smallest elements of list called scores scores sort(print'two smallest'scores[ ]scores[ ]print'two largest'scores[- ]scores[- ]once we sort the listthe smallest values are at the beginning and the largest are at the end example here is program to play simple quiz game num_right question print'what is the capital of france'end'guess input(if guess lower()='paris 'print'correct'num_right+= elseprint'wrong the answer is paris 'print'you have 'num_right'out of right '#question print'which state has only one neighbor'end'guess input(if guess lower()='maine 'print'correct'num_right+= elseprint'wrong the answer is maine 'print'you have 'num_right'out of right'
9,217
lists the code worksbut it is very tedious if we want to add more questionswe have to copy and paste one of these blocks of code and then change bunch of things if we decide to change one of the questions or the order of the questionsthen there is fair amount of rewriting involved if we decide to change the design of the gamelike not telling the user the correct answerthen every single block of code has to be rewritten tedious code like this can often be greatly simplified with lists and loopsquestions 'what is the capital of france''which state has only one neighbor'answers 'paris ''maine 'num_right for in range(len(questions))guess input(questions[ ]if guess lower()==answers[ilower()print'correct 'num_right=num_right+ elseprint'wrong the answer is 'answers[ ]print'you have 'num_right'out of ' + 'right 'if you look carefully at this codeyou will see that the code in the loop is the nearly the same as the code of one of the blocks in the previous programexcept that in the statements where we print the questions and answerswe use questions[iand answers[iin place of the actual text of the questions themselves this illustrates the general techniqueif you find yourself repeating the same code over and overtry lists and for loop the few parts of your repetitious code that are varying are where the list code will go the benefits of this are that to change questionadd questionor change the orderonly the questions and answers lists need to be changed alsoif you want to make change to the programlike not telling the user the correct answerthen all you have to do is modify single lineinstead of twenty copies of that line spread throughout the program exercises write program that asks the user to enter list of integers do the following(aprint the total number of items in the list (bprint the last item in the list (cprint the list in reverse order (dprint yes if the list contains and no otherwise (eprint the number of fives in the list (fremove the first and last items from the listsort the remaining itemsand print the result
9,218
(gprint how many integers in the list are less than write program that generates list of random numbers between and (aprint the list (bprint the average of the elements in the list (cprint the largest and smallest values in the list (dprint the second largest and second smallest entries in the list (eprint how many even numbers are in the list start with the list [ , , do the following(aset the second entry (index to (badd and to the end of the list (cremove the first entry from the list (dsort the list (edouble the list (finsert at index the final list should equal [ , , , , , , , , , , ask the user to enter list containing numbers between and then replace all of the entries in the list that are greater than with ask the user to enter list of strings create new list that consists of those strings with their first characters removed create the following lists using for loop (aa list consisting of the integers through (ba list containing the squares of the integers through (cthe list [' ','bb','ccc','dddd'that ends with copies of the letter write program that takes any two lists and of the same size and adds their elements together to form new list whose elements are sums of the corresponding elements in and for instanceif =[ , , and =[ , , ]then should equal [ , , write program that asks the user for an integer and creates list that consists of the factors of that integer when playing games where you have to roll two diceit is nice to know the odds of each roll for instancethe odds of rolling are about %and the odds of rolling are about you can compute these mathematicallybut if you don' know the mathyou can write program to do it to do thisyour program should simulate rolling two dice about , times and compute and print out the percentage of rolls that come out to be
9,219
lists write program that rotates the elements of list so that the element at the first index moves to the second indexthe element in the second index moves to the third indexetc and the element in the last index moves to the first index using for loopcreate the list belowwhich consists of ones separated by increasingly many zeroes the last two ones in the list should be separated by ten zeroes [ , , , , , , , , , , , , , , , write program that generates random integers that are either or then find the longest run of zerosthe largest number of zeros in row for instancethe longest run of zeros in [ , , , , , , , , , , is write program that removes any repeated items from list so that each item appears at most once for instancethe list [ , , , , , , , would become [ , , , , write program that asks the user to enter length in feet the program should then give the user the option to convert from feet into inchesyardsmilesmillimeterscentimetersmetersor kilometers say if the user enters then the program converts to inchesif they enter then the program converts to yardsetc while this can be done with if statementsit is much shorter with lists and it is also easier to add new conversions if you use lists there is provably unbreakable cipher called one-time pad the way it works is you shift each character of the message by random amount between and characterswrapping around the alphabet if necessary for instanceif the current character is and the shift is then the new character is each character gets its own shiftso there needs to be as many random shifts as there are characters in the message as an examplesuppose the user enters secret the program should generate random shift between and for each character suppose the randomly generated shifts are and the encrypted message would be thebmv (awrite program that asks the user for message and encrypts the message using the one-time pad first convert the string to lowercase any spaces and punctuation in the string should be left unchanged for examplesecret!!becomes thebmv!!using the shifts above (bwrite program to decrypt string encrypted as above the reason it is called one-time-pad is that the list of random shifts should only be used once it becomes easily breakable if the same random shifts are used for more than one message moreoverit is only provably unbreakable if the random numbers are truly randomand the numbers generated by randint are not truly random for this problemjust use randintbut for cryptographically safe random numberssee section
9,220
more with lists lists and the random module there are some nice functions in the random module that work on lists function description choice(lpicks random item from sample( ,npicks group of random items from shuffle(lshuffles the items of note the shuffle function modifies the original listso if you don' want your list changedyou'll need to make copy of it example we can use choice to pick name from list of names from random import choice names 'joe ''bob ''sue ''sally 'current_player choice(namesexample the sample function is similar to choice whereas choice picks one item from listsample can be used to pick several from random import sample names 'joe ''bob ''sue ''sally 'team sample(names
9,221
more with lists example the choice function also works with stringspicking random character from string here is an example that uses choice to fill the screen with bunch of random characters from random import choice 'abcdefghijklmnopqrstuvwxyz !@#$%^&*(for in range( )print(choice( )end''example here is nice use of shuffle to pick random ordering of players in game from random import shuffle players 'joe ''bob ''sue ''sally 'shuffle(playersfor in playersprint( 'it is your turn 'code to play the game goes here example here we use shuffle divide group of people into teams of two assume we are given list called names shuffle(namesteams [for in range( ,len(names), )teams append([names[ ]names[ + ]]each item in teams is list of two names the way the code works is we shuffle the names so they are in random order the first two names in the shuffled list become the first teamthe next two names become the second teametc notice that we use the optional third argument to range to skip ahead by two through the list of names split the split method returns list of the words of string the method assumes that words are separated by whitespacewhich can be either spacestabs or newline characters here is an examples 'hithis is test print( split()['hi!''this''is'' ''test 'as we can seesince split breaks up the string at spacesthe punctuation will be part of the words there is module called string that containsamong other thingsa string variable called punctuation that contains common punctuation we can remove the punctuation from string with the following code
9,222
from string import punctuation for in punctuations replace( ''example here is program that counts how many times certain word occurs in string from string import punctuation input'enter string'for in punctuations replace( '' lower( split(word input'enter word'print(word'appears ' count(word)'times 'optional argument the split method takes an optional argument that allows it to break the string at places other than spaces here is an examples '- print( split'')[' '' '' '' ' join the join method is in some sense the opposite of split it is string method that takes list of strings and joins them together into single string here are some examplesusing the list [' ',' ',' 'operation result join(la 'join(labc 'join(labc '***join(la*** *** example write program that creates an anagram of given word an anagram of word uses the same letters as the word but in different order for instancetwo anagrams of the word there are three and ether don' worry about whether the anagram is real word or not
9,223
more with lists this sounds like something we could use shuffle forbut shuffle only works with lists what we need to do is convert our string into listuse shuffle on itand then convert the list back into string to turn string into listwe can use list( (see section to turn the list back into stringwe will use join from random import shuffle word input'enter word'letter_list list(wordshuffle(letter_listanagram 'join(letter_listprint(anagram list comprehensions list comprehensions are powerful way to create lists here is simple examplel [ for in range( )this creates the list [ , , , , notice that the syntax of list comprehension is somewhat reminiscent of set notation in mathematics here are couple more examples of list comprehensions for these examplesassume the followingstring 'hello [ , , , , 'one ''two ''three ''four ''five ''six 'list comprehension resulting list [ for in range( )[ , , , , , , , , , [ ** for in range( , )[ * for in [ , , , , , , [ * for in string[ [ for in ['hh','ee','ll','ll','oo'[ for in if < [ , , [ [ for in if len( )== [' ',' ',' '[ , , , , [' ',' ',' ',' ',' ',' 'as we see in the last two exampleswe can add an if to list comprehension compare the last example with the long way of building the listl [for in mif len( )== append(mmultiple fors you can use more than one for in list comprehension
9,224
[[ ,jfor in range( for in range( )[[ ][ ][ ][ ]this is the equivalent of the following codel [for in range( )for in range( ) append([ , ]here is another example[[ ,jfor in range( for in range( )[[ ][ ][ ][ ][ ][ ] using list comprehensions to further demonstrate the power of list comprehensionswe will do the first four examples of section in one line apiece using list comprehensions example write program that generates list of random numbers between and [randint( , for in range( )example replace each element in list with its square [ ** for in lexample count how many items in list are greater than len([ for in if > ]example given list that contains numbers between and create new list whose first element is how many ones are in lwhose second element is how many twos are in letc frequencies [ count(ifor in range( , )another example the join method can often be used with list comprehensions to quickly build up string here we create string that contains random assortment of letters from random import choice alphabet 'abcdefghijklmnopqrstuvwxyz 'join([choice(alphabetfor in range( )]
9,225
more with lists one more example suppose we have list whose elements are lists of size like belowl [[ , ][ , ][ , ]if we want to flip the order of the entries in the listswe can use the following list comprehensionm [[ ,xfor , in [[ ][ ][ ]note you can certainly get away without using list comprehensionsbut once you get the hang of themyou'll find they are both quicker to write and easier to read than the longer ways of creating lists two-dimensional lists there are number of common things that can be represented by two-dimensional listslike tictac-toe board or the pixels on computer screen in pythonone way to create two-dimensional list is to create list whose items are themselves lists here is an examplel [[ , , ][ , , ][ , , ]indexing we use two indices to access individual items to get the entry in row rcolumn cuse the followingl[ ][cprinting two-dimensional list to print two-dimensional listyou can use nested for loops the following example prints listfor in range( )for in range( )print( [ ][ ]end="print(another option is to use the pprint function of the pprint module this function is used to "pretty-printits argument here is an example to print list lfrom pprint import pprint pprint(lthe pprint function can be used to nicely print ordinary lists and other objects in python working with two-dimensional lists nested for loopslike the ones used in printing twodimensional listcan also be used to process the items in two-dimensional list here is an example that counts how many entries in list are even
9,226
count for in range( )for in range( )if [ ][ ]% == count count this can also be done with list comprehensioncount sum([ for in range( for in range( if [ ][ ]% == ]creating large two-dimensional lists belowto create larger listyou can use list comprehension like [[ ]* for in range( )this creates list of zeroes with rows and columns picking out rows and columns to get the row of (starting at row )use the followingl[rto get the column of (starting at column )use list comprehension[ [ ][cfor in range(len( ))flattening list to flatten two-dimensional listthat isreturn one-dimensional list of its elementsuse the following[ for row in for in rowfor instancesuppose we have the following listl [[ , , ][ , , ][ , , ]the flattened list will be[ higher dimensions creating and using -dimensional and higher lists is similar here we create listl [[[ ]* for in range( )for in range( )it is list whose items are lists of lists the first entry in the list is [ ][ ][
9,227
more with lists exercises write program that asks the user to enter some text and then counts how many articles are in the text articles are the words ' ''an'and 'the write program that allows the user to enter five numbers (read as stringscreate string that consists of the user' numbers separated by plus signs for instanceif the user enters and then the string should be ' + + + + (aask the user to enter sentence and print out the third word of the sentence (bask the user to enter sentence and print out every third word of the sentence (awrite program that asks the user to enter sentence and then randomly rearranges the words of the sentence don' worry about getting punctuation or capitalization correct (bdo the above problembut now make sure that the sentence starts with capitalthat the original first word is not capitalized if it comes in the middle of the sentenceand that the period is in the right place write simple quote-of-the-day program the program should contain list of quotesand when the user runs the programa randomly selected quote should be printed write simple lottery drawing program the lottery drawing should consist of six different numbers between and write program that estimates the average number of drawings it takes before the user' numbers are picked in lottery that consists of correctly picking six different numbers that are between and to do thisrun loop times that randomly generates set of user numbers and simulates drawings until the user' numbers are drawn find the average number of drawings needed over the times the loop runs write program that simulates drawing names out of hat in this drawingthe number of hat entries each person gets may vary allow the user to input list of names and list of how many entries each person has in the drawingand print out who wins the drawing write simple quiz game that has list of ten questions and list of answers to those questions the game should give the player four randomly selected questions to answer it should ask the questions one-by-oneand tell the player whether they got the question right or wrong at the end it should print out how many out of four they got right write censoring program allow the user to enter some text and your program should print out the text with all the curse words starred out the number of stars should match the length of the curse word for the purposes of this programjust use the"cursewords darndangfreakinheckand shoot sample output is belowenter some textoh shooti thought had the dang problem figured out darn it oh wellit was heck of freakin try oh ***** thought had the ***problem figured out ***it oh wellit was ***of *****try
9,228
section described how to use the shuffle method to create random anagram of string use the choice method to create random anagram of string write program that gets string from the user containing potential telephone number the program should print valid if it decides the phone number is real phone numberand invalid otherwise phone number is considered valid as long as it is written in the form abc-def-hijk or -abc-def-hijk the dashes must be includedthe phone number should contain only numbers and dashesand the number of digits in each group must be correct test your program with the output shown below enter phone number- valid enter phone numbervalid enter phone numberinvalid enter phone number invalid enter phone number invalid let be list of strings write list comprehensions that create new lists from for each of the following (aa list that consists of the strings of with their first characters removed (ba list of the lengths of the strings of (ca list that consists of only those strings of that are at least three characters long use list comprehension to produce list that consists of all palindromic numbers between and use list comprehension to create the list belowwhich consists of ones separated by increasingly many zeroes the last two ones in the list should be separated by ten zeroes [ , , , , , , , , , , , , , , , let =[ , , , , , , , , , , , , , , use list comprehension to produce list of the gaps between consecutive entries in then find the maximum gap size and the percentage of gaps that have size write program that finds the average of all of the entries in list of integers write program that creates list of random integers between and then do the following(aprint the list (bfind the largest value in the third row (cfind the smallest value in the sixth column
9,229
more with lists write program that creates and prints an list whose entries alternate between and in checkerboard patternstarting with in the upper left corner write program that checks to see if list is magic square in magic squareevery rowcolumnand the two diagonals add up to the same value write program that asks the user to enter length the program should ask them what unit the length is in and what unit they would like to convert it to the possible units are inchesyardsmilesmillimeterscentimetersmetersand kilometers while this can be done with if statementsit is shorter and easier to add on to if you use two-dimensional list of conversionsso please use lists for this problem the following is useful as part of program to play battleship suppose you have list that consists of zeroes and ones ask the user to enter row and column if the entry in the list at that row and column is onethe program should print hit and otherwise it should print miss this exercise is useful in creating memory game randomly generate list of assorted characters such that there are exactly two of each character an example is shown below the following is useful in implementing computer players in number of different games write program that creates list consisting of zeroes and ones your program should then pick random location in the list that contains zero and change it to one if all the entries are onethe program should say so [hintone way to do this is to create new list whose items are the coordinates of all the ones in the list and use the choice method to randomly select one use two-element list to represent set of coordinates here is an old puzzle question you can solve with computer program there is only one five-digit number that is such that every one of the following ten numbers shares exactly one digit in common in the same position as find we usually refer to the entries of two-dimensional list by their row and columnlike below on the left another way is shown below on the right ( , ( , ( , ( , ( , ( , ( , ( , ( , (awrite some code that translates from the left representation to the right one the /and operators will be useful be sure your code works for arrays of any size (bwrite some code that translates from the right representation to the left one
9,230
while loops we have already learned about for loopswhich allow us to repeat things specified number of times sometimesthoughwe need to repeat somethingbut we don' know ahead of time exactly how many times it has to be repeated for instancea game of tic-tac-toe keeps going until someone wins or there are no more moves to be madeso the number of turns will vary from game to game this is situation that would call for while loop examples example let' go back to the first program we wrote back in section the temperature converter one annoying thing about it is that the user has to restart the program for every new temperature while loop will allow the user to repeatedly enter temperatures simple way for the user to indicate that they are done is to have them enter nonsense temperature like - (which is below absolute this is done belowtemp while temp!=- temp eval(input'enter temperature (- to quit)')print'in fahrenheit that is ' / *temp+ look at the while statement first it says that we will keep loopingthat iskeep getting and converting temperaturesas long as the temperature entered is not - as soon as - is enteredthe while loop stops tracing throughthe program first compares temp to - if temp is not - then the program asks for temperature and converts it the program then loops back up and again compares temp to - if temp is not - the program will ask for another temperatureconvert itand then loop back up again and do another comparison it continues this process until the user enters - we need the line temp= at the startas without itwe would get name error the program would
9,231
while loops get to the while statementtry to see if temp is not equal to - and run into problem because temp doesn' yet exist to take care of thiswe just declare temp equal to there is nothing special about the value here we could set it to anything except - (setting it to - would cause the condition on the while loop to be false right from the start and the loop would never run note that is natural to think of the while loop as continuing looping until the user enters - howeverwhen we construct the conditioninstead of thinking about when to stop loopingwe instead need to think in terms of what has to be true in order to keep going while loop is lot like an if statement the difference is that the indented statements in an if block will only be executed oncewhereas the indented statements in while loop are repeatedly executed example one problem with the previous program is that when the user enters in - to quitthe program still converts the value - and doesn' give any message to indicate that the program has ended nicer way to do the program is shown below temp while temp!=- temp eval(input'enter temperature (- to quit)')if temp!=- print'in fahrenheit that is ' / *temp+ elseprint'bye'example when first met if statements in section we wrote program that played simple random number guessing game the problem with that program is that the player only gets one guess we canin sensereplace the if statement in that program with while loop to create program that allows the user to keep guessing until they get it right from random import randint secret_num randint( , guess while guess !secret_numguess eval(input'guess the secret number')print'you finally got it'the condition guess!=secret_num says that as long as the current guess is not correctwe will keep looping in this casethe loop consists of one statementthe input statementand so the program will keep asking the user for guess until their guess is correct we require the line guess= prior to the while loop so that the first time the program reaches the loopthere is something in guess for the program to use in the comparison the exact value of guess doesn' really matter at this point we just want something that is guaranteed to be different than secret_num when the user finally guesses the right answerthe loop ends and program control moves to the print statement after the loopwhich prints congratulatory message to the player
9,232
example we can use while loop to mimic for loopas shown below both loops have the exact same effect for in range( )print(ii= while < print(ii= + remember that the for loop starts with the loop variable equal to and ends with it equal to to use while loop to mimic the for loopwe have to manually create our own loop variable we start by setting it to in the while loop we have the same print statement as in the for loopbut we have another statementi= + to manually increase the loop variablesomething that the for loop does automatically example below is our old friend that converts from fahrenheit to celsius temp eval(input'enter temperature in celsius')print'in fahrenheitthat is ' / *temp+ program that gets input from user may want to check to see that the user has entered valid data the smallest possible temperature is absolute zero- the program below takes absolute zero into accounttemp eval(input'enter temperature in celsius')if temp<- print'that temperature is not possible ')elseprint'in fahrenheitthat is ' / *temp+ one way to improve this is to allow the user to keep reentering the temperature until they enter valid one you may have experienced something similar using an online form to enter phone number or credit card number if you enter an invalid numberyou are told to reenter it in the code belowthe while loop acts very similarly to the if statement in the previous example temp eval(input'enter temperature in celsius')while temp<- temp eval(input'impossible enter valid temperature')print'in fahrenheitthat is ' / *temp+ note that we do not need an else statement herelike we had with the if statement the condition on the while loop guarantees that we will only get to the print statement once the user enters valid temperature until that pointthe program will be stuck in the loopcontinually asking the user for new temperature example as mentioned beforeit is valuable skill is to be able to read code one way to do so is to pretend to be the python interpreter and go through the code line by line let' try it with the
9,233
while loops code below while < print(ii= + print'bye'the variable gets set to to start nextthe program tests the condition on the while loop because is which is less than the code indented under the while statement will get executed this code prints the current value of and then executes the statement = + which adds to the variable is now and the program loops back to the while statement it checks to see if is less than and since is which is less than the indented code should be executed again so we print againadd to itand then loop back to check the while loop condition again we keep doing this until finally gets to at this pointthe while condition will finally not be true anymore and the program jumps down to the first statement after the whilewhich prints byethe end result of the program is the numbers followed by the messagebye infinite loops when working with while loopssooner or later you will accidentally send python into neverending loop here is an examplei= while < print(iin this programthe value of never changes and so the condition < is always true python will continuously print zeroes to stop program caught in never-ending loopuse restart shell under the shell menu you can use this to stop python program before it is finished executing sometimes never-ending loop is what you want simple way to create one is shown belowwhile truestatements to be repeated go here the value true is called boolean value and is discussed further in section the break statement the break statement can be used to break out of for or while loop before the loop is finished
9,234
example here is program that allows the user to enter up to numbers the user can stop early by entering negative number for in range( )num eval(input'enter number')if num< break this could also be accomplished with while loop = num= while num eval(input'enter number')either method is ok in many cases the break statement can help make your code easier to understand and less clumsy example earlier in the we used while loop to allow the user to repeatedly enter temperatures to be converted here ismore or lessthe original version on the left compared with different approach using the break statement temp while temp!=- temp eval(input'')if temp!=- print( / *temp+ elseprint'bye' while truetemp eval(input'')if temp==- print'bye 'break print( / *temp+ the else statement there is an optional else that you can use with break statements the code indented under the else gets executed only if the loop completes without break happening example this is simple example based off of example of the previous section for in range( )num eval(input'enter number')if num< print'stopped early 'break elseprint'user entered all ten values '
9,235
while loops the program allows the user to enter up to numbers if they enter negativethen the program prints stopped early and asks for no more numbers if the user enters no negativesthen the program prints user entered all ten values example here are two ways to check if an integer num is prime prime number is number whose only divisors are and itself the approach on the left uses while loopwhile the approach on the right uses for/break loopi= while <num and num% != = + if ==numprint'prime 'elseprint'not prime 'for in range( num)if num% == print'not prime 'break elseprint'prime 'the idea behind both approaches is to scan through all the integers between and num- and if any of them is divisorthen we know num is not prime to see if value is divisor of numwe just have to check to see if num% is the idea of the while loop version is we continue looping as long as we haven' found divisor if we get all the way through the loop without finding divisorthen will equal numand in that case the number must be prime the idea of the for/break version is we loop through all the potential divisorsand as soon as we find onewe know the number is not prime and we print not prime and stop looping if we get all the way through the loop without breakingthen we have not found divisor in that case the else block will execute and print that the number is prime the guessing gamemore nicely done it is worth going through step-by-step how to develop program we will modify the guessing game program from section to do the followingthe player only gets five turns the program tells the player after each guess if the number is higher or lower the program prints appropriate messages for when the player wins and loses below is what we want the program to look likeenter your guess ( - ) lower guesses left enter your guess ( - )
9,236
lower guesses left enter your guess ( - ) lower guesses left enter your guess ( - ) higher guesses left enter your guess ( - ) lower guesses left you lose the correct number is firstthink about what we will need in the programwe need random numbersso there will be an import statement at the beginning of the program and randint function somewhere else to allow the user to guess until they either guess right or run out of turnsone solution is to use while loop with condition that takes care of both of these possibilities there will be an input statement to get the user' guess as this is something that is repeatedly doneit will go inside the loop there will be an if statement to take care of the higher/lower thing as this comparison will be done repeatedly and will depend on the user' guessesit will go in the loop after the input statement there will be counting variable to keep track of how many turns the player has taken each time the user makes guessthe count will go up by oneso this statement will also go inside the loop next start coding those things that are easy to dofrom random import randint secret_num randint( , num_guesses while #some condition goes hereguess eval(input'enter your guess ( - )')num_guesses num_guesses higher/lower if statement goes here for the while loopwe want to continue looping as long as the user has not guessed the secret number and as long as the player has not used up all of their guesseswhile guess !secret_num and num_guesses < the higher/lower if statement can be done like this
9,237
while loops if guess secret_numprint'higher ' -num_guesses'guesses left \ 'elif guess secret_numprint'lower ' -num_guesses'guesses left \ 'elseprint'you got it'finallyit would be nice to have message for the player if they run out of turns when they run out of turnsthe while loop will stop looping and program control will shift to whatever comes outside of the loop at this point we can print the messagebut we only want to do so if the reason that the loop stopped is because of the player running out of turns and not because they guessed correctly we can accomplish this with an if statement after the loop this is shown below along with the rest of the completed program from random import randint secret_num randint( , num_guesses guess while guess !secret_num and num_guesses < guess eval(input'enter your guess ( - )')num_guesses num_guesses if guess secret_numprint'higher ' -num_guesses'guesses left \ 'elif guess secret_numprint'lower ' -num_guesses'guesses left \ 'elseprint'you got it'if num_guesses== and guess !secret_numprint'you lose the correct number is 'secret_numhere is an alternative solution using for/break loopfrom random import randint secret_num randint( , for num_guesses in range( )guess eval(input'enter your guess ( - )')if guess secret_numprint'higher ' -num_guesses'guesses left \ 'elif guess secret_numprint'lower ' -num_guesses'guesses left \ 'elseprint'you got it'break elseprint'you lose the correct number is 'secret_num
9,238
exercises the code below prints the numbers from to rewrite the code using while loop to accomplish the same thing for in range( , )print( (awrite program that uses while loop (not for loopto read through string and print the characters of the string one-by-one on separate lines (bmodify the program above to print out every second character of the string good program will make sure that the data its users enter is valid write program that asks the user for weight and converts it from kilograms to pounds whenever the user enters weight below the program should tell them that their entry is invalid and then ask them again to enter weight [hintuse while loopnot an if statement write program that asks the user to enter password if the user enters the right passwordthe program should tell them they are logged in to the system otherwisethe program should ask them to reenter the password the user should only get five tries to enter the passwordafter which point the program should tell them that they are kicked off of the system write program that allows the user to enter any number of test scores the user indicates they are done by entering in negative number print how many of the scores are ' ( or abovealso print out the average modify the higher/lower program so that when there is only one guess leftit says guessnot guesses recall thatgiven string ss index(' 'returns the index of the first in and an error if there is no (awrite program that asks the user for string and letter using while loopthe program should print the index of the first occurrence of that letter and message if the string does not contain the letter (bwrite the above program using for/break loop instead of while loop the gcd (greatest common divisorof two numbers is the largest number that both are divisible by for instancegcd( is because the largest number that both and are divisible by is write program that asks the user for two numbers and computes their gcd shown below is way to compute the gcdcalled euclid' algorithm first compute the remainder of dividing the larger number by the smaller number nextreplace the larger number with the smaller number and the smaller number with the remainder repeat this process until the smaller number is the gcd is the last value of the larger number
9,239
while loops -year old method to compute the square root of is as followsstart with an initial guesssay then compute nexttake that and replace the ' in the previous formula with ' this gives / next replace the in the previous formula with / this gives / / if you keep doing this process of computing the formulagetting resultand plugging it back inthe values will eventually get closer and closer to this method works for numbers other than write program that asks the user for number and uses this method to estimate the square root of the number correct to within - the estimate will be correct to within - when the absolute value of the difference between consecutive values is less than - write program that has list of ten wordssome of which have repeated letters and some which don' write program that picks random word from the list that does not have any repeated letters write program that starts with an list of zeroes and randomly changes exactly ten of those zeroes to ones write program in which you have list that contains seven integers that can be or find the first nonzero entry in the list and change it to if there are no nonzero entriesprint message saying so in there was problem that asked you to write program that lets the user play rock-paper-scissors against the computer in that program there were exactly five rounds rewrite the program so that it is best out of that isthe first player to win three times is the winner write program to play the following simple game the player starts with $ on each turn coin is flipped and the player has to guess heads or tails the player wins $ for each correct guess and loses $ for each incorrect guess the game ends either when the player runs out of money or gets to $ write program to play the following game there is list of several country names and the program randomly picks one the player then has to guess letters in the word one at time before each guess the country name is displayed with correctly guessed letters filled in and the rest of the letters represented with dashes for instanceif the country is canada and the player has correctly guessed adand nthe program would display -ana-da the program should continue until the player either guesses all of the letters of the word or gets five letters wrong
9,240
write text-based version of the game memory the game should generate board (see the exercise from initially the program should display the board as grid of asterisks the user then enters the coordinates of cell the program should display the grid with the character at those coordinates now displayed the user then enters coordinates of another cell the program should now display the grid with the previous character and the new character displayed if the two characters matchthen they should permanently replace the asterisks in those locations otherwisewhen the user enters the next set of coordinatesthose characters should be replaced by asterisks the game continues this way until the player matches everything or runs out of turns you can decide how many turns they player gets ask the user to enter the numerator and denominator of fractionand the digit they want to know for instanceif the user enters numerator of and denominator of and wants to know the th digityour program should print out because and is the th digit one way to do this is to mimic the long division process you may have learned in grade school it can be done in about five lines using the /operator at one point in the program randomly generate list that has exactly ones placed in random locations in the list the rest of the entries should be zeroes randomly generate list where the entries are integers between and with no repeat entries in any row or in any column
9,241
while loops
9,242
miscellaneous topics ii in this we will look at variety of useful things to know strintfloatand list the strintfloatand list functions are used to convert one data type into another str quite often we will want to convert number to string to take advantage of string methods to break the number apart the built-in function str is used to convert things into strings here are some examplesstatement result str( ' str( ' str([ , , ]'[ , , ]int and float the int function converts something into an integer the float function converts something into floating point number here are some examples statement result int(' ' float(' ' int( to convert float to an integerthe int function drops everything after the decimal point
9,243
miscellaneous topics ii list the list function takes something that can be converted into list and makes into list here are two uses of it list(range( )list('abc'[ , , , , [' ',' ',' 'examples example here is an example that finds all the palindromic numbers between and palindromic number is one that is the same backwards as forwardslike or for in range( , ) str(iif == [::- ]print(swe use the str function here to turn the integer into string so we can use slices to reverse it example here is an example that tells person born on january how old they are in birthday 'january year int(birthday[- :]print'you are ' -year'years old 'the year is in the last four characters of birthday we use int to convert those characters into an integer so we can do math with the year example write program that takes number num and adds its digits for instancegiven the number the program should return (which is let us start with -digit example digit str(numanswer int(digit[ ]int(digit[ ]the idea here is that we convert num to string so that we can use indexing to get the two digits separately we then convert each back to an integer using the int function here is version that handles numbers with arbitrarily many digitsdigit str(numanswer for in range(len(digit))answer answer int(digit[ ]we can do the above program in single line using list comprehension answer sum([int(cfor in str(num)]
9,244
example to break decimal numbernumup into its integer and fractional partswe can do the followingipart int(numdpart num int(numfor exampleif num is then ipart is and dpart is example if we want to check to see if number is primewe can do so by checking to see if it has any divisors other than itself and in section we saw code for thisand we had the following for loopfor in range( ,num)this checks for divisibility by the integers num- howeverit turns out that you really only have to check the integers from to the square root of the number for instanceto check if is primeyou only need to check if it is divisible by the integers through as we could then try the following for loopfor in range( ,num* )howeverthis gives an errorbecause num* might not be an integerand the range function needs integers we can use int to correct thisfor in range( ,int(num* )+ )the + at the end is needed due to the range function not including the last value booleans boolean variables in python are variables that can take on two valuestrue and false here are two examples of setting boolean variablesgame_over true highlight_text false booleans can help make your programs more readable they are often used as flag variables or to indicate options booleans are often used as conditions in if statements and while loopsif game_overprint'bye'note the following equivalencesif game_overwhile not game_overif game_over==truewhile game_over==falsenote conditional expressions evaluate to booleans and you can even assign them to variables for instancethe following assigns true to because == evaluates to true ( ==
9,245
miscellaneous topics ii we have seen booleans before the isalpha string method returns true if every character of the string is letter and false otherwise shortcuts shortcut operators operations like count=count+ occur so often that there is shorthand for them here are couple of examplesstatement shorthand count=count+ count+= total=total- total-= prod=prod* prod*= there are also shortcut operators /=%=//=and **an assignment shortcut look at the code below nice shortcut isa another assignment shortcut say we have list with three elements in itand we want to assign those elements to variable names we could do the followingx [ [ [ insteadwe can do thisx, , similarlywe can assign three variables at time like belowx, , , , andas we have seen once beforewe can swap variables using this kind of assignment , , , , shortcuts with conditions here are some handy shortcutsstatement shortcut if == and == and == if == == == if < and < and < if < < <
9,246
short-circuiting say we are writing program that searches list of words for those whose fifth character is 'zwe might try the followingfor in wordsif [ ]=' 'print(wbut with thiswe will occasionally get string index out of range error the problem is that some words in the list might be less than five characters long the following if statementhoweverwill workif len( )>= and [ ]=' 'it might seem like we would still get an error because we are still checking [ ]but there is no error the key to why this works is short-circuiting python starts by checking the first part of the conditionlen( )>= if that condition turns out to be falsethen the whole and condition is guaranteed to be falseand so there is no point in even looking at the second condition so python doesn' bother with the second condition you can rely on this behavior short-circuiting also happens with or conditions in this casepython checks the first part of the or and if it is truethen the whole or is guaranteed to be trueand so python will not bother checking the second part of the or continuation sometimes you'll write long line of code that would be more readable if it were split across two lines to do thisuse backslash character at the end of the line to indicate that the statement continues onto the next line here is an exampleif ' in string or ' in string or ' in string or ' in string or ' in stringmake sure there are no extra spaces after the backslash or you will get an error message if you are entering listdictionaryor the arguments of functionthe backslash can be left outl 'joe ''bob ''sue ''jimmy ''todd ''frank ''mike ''john ''amy ''edgar ''sam ' pass the pass statement does nothing believe it or notsuch thing does have few uses that we will see later
9,247
miscellaneous topics ii string formatting suppose we are writing program that calculates tip on bill of $ when we multiplywe get but we would like to display the result as $ not $ here is how to do ita print'the tip is { fformat( )this uses the format method of strings here is another examplebill tip print'tip${ }total${ fformat(tipbill+tip)the way the format method works is we put pair of curly braces {anywhere that we want formatted value the arguments to the format function are the values we want formattedwith the first argument matching up with the first set of bracesthe second argument with the second set of bracesetc inside each set of curly braces you can specify formatting code to determine how the corresponding argument will be formatted formatting integers to format integersthe formatting code is {:dputting number in front of the allows us to right-justify integers here is an exampleprint'{: dformat( )print'{: dformat( )print'{: dformat( ) the number in these examples says that the value is allotted three spots the value is placed as far right in those three spots as possible and the rest of the slots will be filled by spaces this sort of thing is useful for nicely formatting tables to center integers instead of right-justifyinguse the characterand to left-justifyuse the character print'{:^ dformat( )print'{:^ dformat( )print'{:^ dformat( ) each of these allots five spaces for the integer and centers it within those five spaces putting comma into the formatting code will format the integer with commas the example below prints , , print'{:,dformat( )
9,248
formatting floats to format floating point numberthe formatting code is {:fto only display the number to two decimal placesuse { fthe can be changed to change the number of decimal places you can right-justify floats for example{: fwill allot eight spots for its value--one of those is for the decimal point and two are for the part of the value after the decimal point if the value is then only four spots are needed and the remaining spots are filled by spacescausing the value to be right-justified the and characters center and left-justify floats formatting strings to format stringsthe formatting code is {:shere is an example that centers some textprint'{:^ sformat'hi ')print'{:^ sformat'there')hi thereto right-justify stringuse the characterprint'{:> sformat'hi ')print'{:> sformat'there ')hi therethere is whole lot more that can be done with formatting see the python documentation [ nested loops you can put loops inside of other loops loop inside of another loop is said to be nestedand you canmore or lessnest loops as deeply as you want example print multiplication table for in range( , )for in range( , )print'{: dformat( * )end'print( multiplication table is two-dimensional object to work with itwe use two for loopsone for the horizontal direction and one for the vertical direction the print statement right justifies the products to make them look nice the end='allows us to print several things on each row when we are done printing rowwe use print(to advance things to the next line
9,249
miscellaneous topics ii example common math problem is to find the solutions to system of equations sometimes you want to find only the integer solutionsand this can be little tricky mathematically howeverwe can write program that does brute force search for solutions here we find all the integer solutions (xyto the system where and are both between - and for in range(- , )for in range(- , )if * + * == and - == print( ,yexample pythagorean triple is triple of numbers (xyzsuch that for instance ( is pythagorean triple because pythagorean triples correspond to triangles whose sides are all whole numbers (like -trianglehere is program that finds all the pythagorean triples (xyzwhere and are positive and less than for in range( , )for in range( , )for in range( , )if ** + ** == ** print( , ,zif you run the programyou'll notice that there are redundant solutions for instance( and ( are both listed to get rid of these redundancieschange the second loop so that it runs from to this waywhen is for instancethe first value for that will be searched is rather than and so we won' get the redundant ( also change the third loop so that it runs from to as you look through the solutionsyou might also notice that there are many solutions that are multiples of otherslike ( )and ( are multiples of ( the following program finds only primitive pythagorean triplesthose that aren' multiples of another triple the way it does this is every time new triple is foundit checks to make sure that xyand are not all divisible by the same number for in range( , )for in range( , )for in range( , )if ** + ** == ** for in range( , )if % == and % == and % == break elseprint(( , , )end'example in section we will write game to play tic-tac-toe the board is gridand we will use nested for loops to create it
9,250
example your computer screen is grid of pixels to draw images to the screenwe often use nested for loops--one loop for the horizontal directionand one for the vertical direction see sections and for examples example list comprehensions can contain nested for loops the example below returns list of all the vowels in list of words [char for item in for char in item if char in 'aeiou ' exercises write program that uses list and range to create the list [ , write program that asks the user for weight in kilograms the program should convert the weight to kilogramsformatting the result to one decimal place write program that asks the user to enter word rearrange all the letters of the word in alphabetical order and print out the resulting word for exampleabracadabra should become aaaaabbcdrr write program that takes list of ten prices and ten productsapplies an discount to each of the prices displays the output like belowright-justified and nicely formatted apples oranges pears $ use the following two lists and the format method to create list of card names in the format card value of suit name (for example'two of clubs'suits 'hearts ''diamonds ''clubs ''spades 'values 'one ''two ''three ''four ''five ''six ''seven ''eight ''nine ''ten ''jack ''queen ''king ''ace ' write program that uses boolean flag variable in determining whether two lists have any items in common write program that creates the list [ , , , , ]where the entries have an ever increasing number of oneswith the last entry having ones write program to find all numbers between and that are divisible by and end in write program to determine how many of the numbers between and contain the digit
9,251
miscellaneous topics ii adding certain numbers to their reversals sometimes produces palindromic number for instance sometimeswe have to repeat the process for instance and write program that finds both two-digit numbers for which this process must be repeated more than times to obtain palindromic number write program that finds all pairs of six-digit palindromic numbers that are less than apart one such pair is and the number reads the same upside-down as right-side up print out all the numbers between and that read the same upside-down as right-side up the number has the property that if we multiply its digits together and then add the sum of its digits to thatwe get back to that is( ( write program to find all of the numbers less than with this property (there are only nine of them write program to find the smallest positive integer that satisfies the following propertyif you take the leftmost digit and move it all the way to the rightthe number thus obtained is exactly times larger than the original number for instanceif we start with and move the all the way to the rightwe get which is roughly times the original number write program to determine how many zeroes ends with write program that converts decimal height in feet into feet and inches for instancean input of feet should become feet inches write program that repeatedly asks the user to enter height in the format feet'inches(like ' or ' the user indicates they are done entering heights by entering done the program should return count of how many -footers -footers -footersand -footers were entered write program that repeatedly asks the user to enter football score in the format winning score-losing score (like - or - the user indicates they are done entering scores by entering done the program should then output the highest score and the lowest score out of all the scores entered write program that repeatedly asks the user to enter birthday in the format month/day (like / or / the user indicates they are done entering birthdays by entering done the program should return count of how many of those birthdays are in february and how many are on the th of some month (any month write program that asks the user to enter date in the format mm/dd/yy and converts it to more verbose format for exampleshould get converted into february write program that asks the user to enter fraction in the form of string like ' / or ' / the program should reduce the fraction to lowest terms and print out the result write program to find all four solutions to the following problemif starfruit is worth $ mango is worth $ and three oranges together cost $ how many starfruitsmangoesand orangestotaling can be bought for $
9,252
the currency of strange country has coins worth cents and cents write program to determine the largest purchase price that cannot be paid using these two coins here is an old puzzle you can solve using brute force by using computer program to check all the possibilitiesin the calculation every digit is precisely one away from its true value what is the correct calculation write program that finds all integer solutions to pell' equation where and are between and write program that asks the user for number and prints out all the ways to write the number as difference of two perfect squaresx where and are both between and writing number as difference of two squares leads to clever techniques for factoring large numbers write program that simulates all possible rolls of four dice and for each simulated rollfinds the sums of pairs of dice for instanceif the roll is the sums are , and for each of the possible sums from to find the total number of simulated rolls in which the sum appears and what percentage of the simulated rolls had those sums appear output the totals and percentagesnicely formattedwith the percentages formatted to one decimal place to check your workyou should find that the sum comes up in rollswhich is of the rolls in magic squareeach roweach columnand both diagonals add up to the same number partially filled magic square is shown below write program to check through all the possibilities to fill in the magic square the following is useful as part of program to play minesweeper suppose you have list that consists of zeros and ' write program that creates new list that has ' in the same placebut the zeroes are replaced by counts of how many ' are in adjacent cells (adjacent either horizontallyverticallyor diagonallyan example is shown below [hintshort-circuiting may be helpful for avoiding index-out-of-range errors pascal' triangle is shown below on the outside are ' and each other number is the sum of the two numbers directly above it write program to generate pascal' triangle allow the user to specify the number of rows be sure that it is nicely formattedlike below
9,253
miscellaneous topics ii given two dates entered as strings in the form mm/dd/yyyy where the years are between and determine how many days apart they are here is bit of information that may be usefulleap years between and occur exactly every four yearsstarting at february has days during leap year novemberapriljuneand september each have days the other months have days monte carlo simulations can be used to estimate all sorts of thingsincluding probabilities of coin flip and dice events as an exampleto estimate the probability of rolling pair of sixes with two dicewe could use random integers to simulate the dice and run the simulation thousands of timescounting what percentage of the time pair of sixes comes up (aestimate the probability of rolling yahtzee in single roll of five dice that is estimate the probability that when rolling five dice they all come out to be the same number (bestimate the probability of rolling large straight in single roll of five dice large straight is roll where the dice come out - - or - - in any order (cestimate the average longest run of heads or tails when flipping coin times (destimate the average number of coin flips it takes before five heads in row come up (eestimate the average number of coin flips it takes before the string comes upwhere is string of heads and tailslike hhtth
9,254
dictionaries dictionary is more general version of list here is list that contains the number of days in the months of the yeardays [ if we want the number of days in januaryuse days[ december is days[ or days[- here is dictionary of the days in the months of the yeardays 'january ': 'february ': 'march ': 'april ': 'may ': 'june ': 'july ': 'august ': 'september ': 'october ': 'november ': 'december ': to get the number of days in januarywe use days['january'one benefit of using dictionaries here is the code is more readableand we don' have to figure out which index in the list given month is at dictionaries have number of other usesas well basics creating dictionaries here is simple dictionaryd ' ': ' ': to declare dictionary we enclose it in curly braces{each entry consists of pair separated by colon the first part of the pair is called the key and the second is the value the key acts like an index so in the first pair' ': the key is ' 'the value is and [' 'gives keys are often stringsbut they can be integersfloatsand many other things as well you can mix different types of keys in the same dictionary and different types of valuestoo changing dictionaries let' start with this dictionaryd ' ': ' ':
9,255
dictionaries to change [' 'to do ' ']= to add new entry to the dictionarywe can just assign itlike belowd' ']= note that this sort of thing does not work with lists doing [ ]= on list with two elements would produce an index out of range error but it does work with dictionaries to delete an entry from dictionaryuse the del operatordel ' 'empty dictionary 'for strings the empty dictionary is {}which is the dictionary equivalent of [for lists or important note the order of items in dictionary will not necessarily be the order in which put them into the dictionary internallypython rearranges things in dictionary in order to optimize performance dictionary examples example you can use dictionary as an actual dictionary of definitionsd 'dog 'has tail and goes woof''cat 'says meow ''mouse 'chased by cats 'here is an example of the dictionary in useword input'enter word'print'the definition is' [word]enter wordmouse the definition ischased by cats example the following dictionary is useful in program that works with roman numerals numerals ' ': ' ': ' ': ' ': ' ': ' ': ' ': example in the game scrabbleeach letter has point value associated with it we can use the following dictionary for the letter valuespoints ' ': ' ': ' ': ' ': ' ': ' ': ' ': ' ': ' ': ' ': ' ': ' ': ' ': ' ': ' ': ' ': ' ': ' ': ' ': ' ': ' ': ' ': ' ': ' ': ' ': ' ':
9,256
to score wordwe can do the followingscore sum([points[cfor in word]orif you prefer the long waytotal for in wordtotal +points[cexample dictionary provides nice way to represent deck of cardsdeck ['value ': 'suit ':cfor in 'spades ''clubs ''hearts ''diamonds 'for in range( , )the deck is actually list of dictionaries the shuffle method can be used to shuffle the deckshuffle(deckthe first card in the deck is deck[ to get the value and the suit of the cardwe would use the followingdeck[ ]'value 'deck[ ]'suit ' working with dictionaries copying dictionaries just like for listsmaking copies of dictionaries is little tricky for reasons we will cover later to copy dictionaryuse its copy method here is an exampled copy(in the in operator is used to tell if something is key in the dictionary for instancesay we have the following dictionaryd ' ': ' ': referring to key that is not in the dictionary will produce an error for instanceprint( [' ']will fail to prevent this errorwe can use the in operator to check first if key is in the dictionary before trying to use the key here is an exampleletter input'enter letter'if letter in dprint'the value is ' [letter]elseprint'not in dictionary 'you can also use not in to see if key is not in the dictionary
9,257
dictionaries looping looping through dictionaries is similar to looping through lists here is an example that prints the keys in dictionaryfor key in dprint(keyhere is an example that prints the valuesfor key in dprint( [key]lists of keys and values the following table illustrates the ways to get lists of keys and values from dictionary it uses the dictionary ={' ': ,' ': statement result description list( [' ',' 'keys of list( values()[ , values of list( items()[(' ', ),(' ', )(key,valuepairs of the pairs returned by items are called tuples tuples are lot like lists they are covered in section here is use of items to find all the keys in dictionary that correspond to value of ' ': ' ': ' ': [ [ for in items(if [ ]== 'ac dict the dict function is another way to create dictionary one use for it is kind of like the opposite of the items methodd dict([' ', ),' ', )]this creates the dictionary {' ': ,' ': this way of building dictionary is useful if your program needs to construct dictionary while it is running dictionary comprehensions dictionary comprehensions work similarly to list comprehensions the following simple example creates dictionary from list of wordswhere the values are the lengths of the wordsd { len(sfor in words counting words we can use dictionaries to count how frequently certain words appear in text
9,258
in section we will learn how to read from text file for nowhere' line of code that reads the entire contents of file containing the text of shakespeare' romeo and juliet and stores the contents in string called texttext open'romeoandjuliet txt 'read(to get at the individual wordswe will use the split method to turn the string into list of its individual words alsobecause some words may be capitalizedwe will convert the whole string to lowercase we also have to remove punctuation from string import punctuation text text lower(for in punctuationtext text replace( ''words text split(next comes the dictionary code that does the counting the dictionary keys will be the words from the text and the values will be counts of how many time each word appears we start with an empty dictionary then for every word in the list of wordsif we have seen the word beforewe add one to its countand otherwise we set the count for that word equal to here is the coded {for in wordsif in dd[wd[ elsed[ once we have created the dictionarywe can use the following code to print the items in alphabetical orderitems list( items()items sort(for in itemsprint(ithe way this works is little tricky remember that items(returns list of pairs (called tuples)which are lot like lists when we sort list of tuplesthe sorting is done by the first entrywhich in this case is the word so the sorting is done alphabetically if we instead want to order things by frequencywe can flip the order of the tuples and then sortitems list( items()items [( [ ] [ ]for in itemsitems sort(for in itemsprint(ihere is the code all togetherfrom string import punctuation read from fileremove caps and punctuationand split into words text open'romeoandjuliet txt 'read(
9,259
dictionaries text text lower(for in punctuationtext text replace( ''words text split(build the dictionary of frequencies {for in wordsif in dd[wd[ elsed[ print in alphabetical order items list( items()items sort(for in itemsprint(iprint in order from least to most common items list( items()items [( [ ] [ ]for in itemsitems sort(for in itemsprint(isee section for another approach to word frequencies exercises write program that repeatedly asks the user to enter product names and prices store all of these in dictionary whose keys are the product names and whose values are the prices when the user is done entering products and pricesallow them to repeatedly enter product name and print the corresponding price or message if the product is not in the dictionary using the dictionary created in the previous problemallow the user to enter dollar amount and print out all the products whose price is less than that amount for this problemuse the dictionary from the beginning of this whose keys are month names and whose values are the number of days in the corresponding months (aask the user to enter month name and use the dictionary to tell them how many days are in the month (bprint out all of the keys in alphabetical order (cprint out all of the months with days (dprint out the (key-valuepairs sorted by the number of days in each month
9,260
(emodify the program from part (aand the dictionary so that the user does not have to know how to spell the month name exactly that isall they have to do is spell the first three letters of the month name correctly write program that uses dictionary that contains ten user names and passwords the program should ask the user to enter their username and password if the username is not in the dictionarythe program should indicate that the person is not valid user of the system if the username is in the dictionarybut the user does not enter the right passwordthe program should say that the password is invalid if the password is correctthen the program should tell the user that they are now logged in to the system repeatedly ask the user to enter team name and the how many games the team won and how many they lost store this information in dictionary where the keys are the team names and the values are lists of the form [winslosses(ausing the dictionary created aboveallow the user to enter team name and print out the team' winning percentage (busing the dictionarycreate list whose entries are the number of wins of each team (cusing the dictionarycreate list of all those teams that have winning records repeatedly ask the user to enter game scores in format like team score team score store this information in dictionary where the keys are the team names and the values are lists of the form [winslosses create list of numbers then write program that creates dictionary whose keys are the numbers and whose values are the how many times the number occurs then print the three most common numbers using the card dictionary from earlier in this create simple card game that deals two players three cards each the player with the highest card wins if there is tiethen compare the second highest card andif necessarythe third highest if all three cards have the same valuethen the game is draw using the card dictionary from earlier in the deal out three cards determine the following(aif the three cards form flush (all of the same suit(bif there is three-of- -kind (all of the same value(cif there is pairbut not three-of- -kind (dif the three cards form straight (all in rowlike ( or ( jackqueen) using the card dictionary from earlier in the run monte carlo simulation to estimate the probability of being dealt flush in five card hand see exercise of for more about monte carlo simulations in section we met the substitution cipher this cipher replaces every letter with different letter for instance every might be replaced with an eevery might be replaced with an
9,261
dictionaries aetc write program that asks the user to enter two strings then determine if the second string could be an encoded version of the first one with substitution cipher for instancecxyz is not an encoded version of book because got mapped to two separate letters alsocxxk is not an encoded version of bookbecause got mapped to itself on the other handcxxz would be an encoding of book this problem can be done with or without dictionary below are the notes used in musicc cd de fg ga ab the notes for the major chord are ceg mathematical way to get this is that is steps past and is steps past this works for any base for examplethe notes for major are df# we can represent the major chord steps as list with two elements[ , the corresponding lists for some other chord types are shown belowminor augmented fifth minor fifth major sixth minor sixth [ , [ , [ , [ , , [ , , dominant seventh minor seventh major seventh diminished seventh [ , , [ , , [ , , [ , , write program that asks the user for the key and the chord type and prints out the notes of the chord use dictionary whose keys are the (musicalkeys and whose values are the lists of steps suppose you are given the following list of stringsl 'aabaabac ''cabaabca ''aaabbcba ''aabacbab ''acababba 'patterns like this show up in many placesincluding dna sequencing the user has string of their own with only some letters filled in and the rest as asterisks an example is ** ***the user would like to know which of the strings in the list fit with their pattern in the example just giventhe matching strings are the first and fourth one way to solve this problem is to create dictionary whose keys are the indices in the user' string of the non-asterisk characters and whose values are those characters write program implementing this approach (or some other approachto find the strings that match user-entered string dictionaries provide convenient way to store structured data here is an example dictionaryd=['name ''todd ''phone '' - ''email ''todd@mail net '}'name ''helga ''phone '' - ''email ''helga@mail net '}'name ''princess ''phone '' - ''email '''}'name ''lj ''phone '' - ''email ''lj@mail net '}write program that reads through any dictionary like this and prints the following(aall the users whose phone number ends in an (ball the users that don' have an email address listed
9,262
the following problem is from try it againthis time using dictionary whose keys are the names of the time zones and whose values are offsets from the eastern time zone write program that converts time from one time zone to another the user enters the time in the usual american waysuch as : pm or : am the first time zone the user enters is that of the original time and the second is the desired time zone the possible time zones are easterncentralmountainor pacific time : pm starting zonepacific ending zoneeastern : am (awrite program that converts roman numerals into ordinary numbers here are the conversionsm= = = = = = = don' forget about things like iv being and xl being (bwrite program that converts ordinary numbers into roman numerals
9,263
dictionaries
9,264
text files there is ton of interesting data to be found on the internet stored in text files in this we will learn how to work with data stored in text files reading from files suppose we have text file called example txt whose contents are shown belowand we want to read its contents into python there are several ways to do so we will look at two of them hello this is text file bye the first way to read text file uses list comprehension to load the file line-by-line into listlines [line strip(for line in open'example txt ')the list lines is now 'hello ''this is text file ''bye'the string method strip removes any whitespace characters from the beginning and end of string if we had not used iteach line would contain newline character at the end of the line this is usually not what we want notestrip removes whitespace from both the beginning and end of the line use rstrip if you need to preserve whitespace at the beginning of the line the second way of reading text file loads the entire file into strings open'example txt 'read(the string is now 'hello \nthis is text file \nbye
9,265
text files directories say your program opens filelike belows open'file txt 'read(the file is assumed to be in the same directory as your program itself if it is in different directorythen you need to specify thatlike belows open' :/users/heinold/desktop/file txt 'read( writing to files there are also several ways to write to files we will look at one way here we will be writing to file called writefile txt open'writefile txt '' 'print'this is line 'file=fprint'this is line 'file=ff close(we first have to open the file that is what the first line doeswith the 'windicating that we want to be able to write to the file python creates what is called file object to represent the fileand we give that object the name this is what we use to refer to the file to write to the filewe use the print statement with the optional file argument that specifies the file to write to when we are done writingwe should close the file to make sure all of our changes take be careful here because if writefile txt already existsits contents will be overwritten examples example write program that reads list of temperatures from file called temps txtconverts those temperatures to fahrenheitand writes the results to file called ftemps txt file open'ftemps txt '' 'temperatures [line strip(for line in open'temps txt ')for in temperaturesprint(int( )* / + file=file file close(example in section we wrote simple quiz game the questions and answers were both contained in lists hard-coded into the program instead of thatwe can store the questions and answers in files that wayif you decide to change the questions or answersyou just have to change their files moreoverif you decide to give the program to someone else who doesn' know
9,266
pythonthey can easily create their own lists of questions and answers to do thiswe just replace the lines that create the lists with the followingquestions [line strip(for line in open'questions txt ')answers [line strip(for line in open'answers txt ')example say you have text file that contains the results of every - ncaa basketball game (you can find such file at www kenpom com typical line of the file looks like thisrobert morris mount st mary' below is program that scans through the file to find the most lopsided gamethe one where the winning team had the largest margin of victory lines [line strip(for line in open'scores txt ')games [line split''for line in linesprint(max([abs(int( [ ])-int( [ ])for in games])we use the split method to break each line into lists of its component parts the scores are at indices and to find the maximum differencewe can use list comprehension to create list of all the margins of victories and use max to find the maximum the maximum turns out to be unfortunatelythe method above does not tell us anything else about the game in order to do thatwe resort to the longer way to find maximumsdescribed in section this allows us to store information about the game as we search for the largest margin of victory lines [line strip(for line in open'scores txt ')games [line split''for line in linesbiggest_diff for in gamesdiff abs(int( [ ])-int( [ ])if diff>biggest_diffbiggest_diff diff game_info print(game_info[''saleminternational'' 'marshall'' ' wordplay if you like wordsyou can have lot of fun with wordlistwhich is text file where each line contains different word quick web search will turn up variety of different wordlistsranging from lists of common english words to lists containing practically every english word
9,267
text files assuming the wordlist file is wordlist txtwe can load the words into list using the line below wordlist [line strip(for line in open'wordlist txt ')example print all three letter words for word in wordlistif len(word)== print(wordnote that this and most of the upcoming examples can be done with list comprehensionsprint([word for word in wordlist if len(word)== ]example print all the words that start with gn or kn for word in wordlistif word[: ]='gn or word[: ]='kn 'print(wordexample determine what percentage of words start with vowel count for word in wordlistif word[ in 'aeiou 'count=count+ print( *count/len(wordlist)example print all -letter words that start with th and end in ly things like this are good for cheating at crosswords for word in wordlistif len(word)== and word[: ]='th and word[- :]='ly 'print(wordexample print the first ten words that start with = while wordlist[ ][ ]!' ' = + print(wordlist[ : +
9,268
note this is not very efficient way of doing things since we have to scan through most of the list binary search would be more efficientbut the above approach still runs almost instantly even for large files example find the longest word that can be made using only the letters abcdand largest for word in wordlistfor in wordif not in 'abcde 'break elseif len(word)>largestlargest=len(wordlargest_word=word print(largest_wordthe way this program works is for every word in the wordlistwe use for/else loop (section to scan through the word looking checking each character to see if it is an abcdor if any letter isn' one of thesethen we break out of the loop and move on to the next word on the other handif we get all the way through the loopthen we go to else block in that blockwe use modification of the technique from section for finding maximum exercises you are given file called class_scores txtwhere each line of the file contains oneword username and test score separated by spaceslike belowgwashington jadams write code that scans through the fileadds points to each test scoreand outputs the usernames and new test scores to new filescores txt you are given file called grades txtwhere each line of the file contains one-word student username and three test scores separated by spaceslike belowgwashington jadams write code that scans through the file and determines how many students passed all three tests you are given file called logfile txt that lists log-on and log-off times for users of system typical line of the file looks like thisvan rossum : :
9,269
text files each line has three entries separated by commasa usernamea log-on timeand log-off time times are given in -hour format you may assume that all log-ons and log-offs occur within single workday write program that scans through the file and prints out all users who were online for at least an hour you are given file called students txt typical line in the file looks likewalter melon melon@email msmary edu - there is namean email addressand phone numbereach separated by tabs write program that reads through the file line-by-lineand for each linecapitalizes the first letter of the first and last name and adds the area code to the phone number your program should write this to new file called students txt here is what the first line of the new file should look likewalter melon melon@email msmary edu you are given file namelist txt that contains bunch of names some of the names are first name and last name separated by spaceslike george washingtonwhile others have middle namelike john quincy adams there are no names consisting of just one word or more than three words write program that asks the user to enter initialslike gw or jqaand prints all the names that match those initials note that initials like ja should match both john adams and john quincy adams you are given file namelist txt that contains bunch of names print out all the names in the list in which the vowels aeioand appear in order (with repeats possiblethe first vowel in the name must be and after the first uit is okay for there to be other vowels an example is ace elvin coulson you are given file called baseball txt typical line of the file starts like below ichiro suzuki sea [more statseach entry is separated by tab\ the first entry is the player' name and the second is their team following that are statistics home runs are the seventh stat and stolen bases are the eleventh print out all the players who have at least home runs and at least stolen bases for this problemuse the file of ncaa basketball scores as described in section (afind the average of the points scored over all the games in the file (bpick your favorite team and scan through the file to determine how many games they won and how many games they lost (cfind the team(sthat lost by or more points the most times (dfind all the teams that averaged at least points game
9,270
(efind all the teams that had winning records but were collectively outscored by their opponents team is collectively outscored by their opponents if the total number of points the team scored over all their games is less than the total number of points their opponents scored in their games against the team benford' law states that in real data where the values are spread across several orders of magnitudeabout of the values will start with the number whereas only about of the values will start with the number this is contrary to what we might expectnamely that values starting with and would be equally likely using the file expenses txt which consists of number of costs from an expense accountdetermine what percentage start with each of the digits through this technique is used by accountants to detect fraud wordplay use the file wordlist txt for this problem find the following(aall words ending in ime (ball words whose secondthirdand fourth letters are ave (chow many words contain at least one of the letters rstlne (dthe percentage of words that contain at least one of the letters rstlne (eall words with no vowels (fall words that contain every vowel (gwhether there are more ten-letter words or seven-letter words (hthe longest word in the list (iall palindromes (jall words that are words in reverselike rat and tar (ksame as abovebut only print one word out of each pair (lall words that contain double letters next each other like aardvark or bookexcluding words that end in lly (mall words that contain that isn' followed by (nall words that contain zu anywhere in the word (oall words that contain ab in multiple placeslike habitable (pall words with four or more vowels in row (qall words that contain both and (rall words whose first letter is athird letter is and fifth letter is (sall two-letter words (tall four-letter words that start and end with the same letter (uall words that contain at least nine vowels (vall words that contain each of the letters abcdeand in any order there may be other letters in the word two examples are backfield and feedback (wall words whose first four and last four letters are the same
9,271
text files (xall words of the form abcd*dcbawhere is arbitrarily long sequence of letters (yall groups of wordslike pat pet pit pot putwhere each word is lettersall words share the same first and last lettersand the middle letter runs through all vowels (zthe word that has the most ' write program to help with word games the user enters word and the program uses the wordlist to determine if the user' word is real word or not suppose we write all the words in the wordlist backwards and then arrange these backwards words alphabetically write program that prints the last word in this modified wordlist print out all combinations of the string 'pythonplus three letter english word capitalize the first letter of the three letter word example combinations are 'pythoncat''pythondog'and 'pythontagthese are valid combinations because catdogand tag are english words on the other hand'pythonqqzwould not be valid combination because qqz is not an english word use wordlist to determine which three letter combinations are words write simple spell-checking program the user should enter string and the program should print out list of all the words it thinks are misspelled these would be all the words it cannot find in wordlist crossword cheaterwhen working on crossword puzzleoften you will have word where you know several of the lettersbut not all of them you can write computer program to help you for the programthe user should be able to input word with the letters they know filled in and asterisks for those they don' know the program should print out list of all words that fit that description for examplethe input th***ly should return all the words that could worknamely thickly and thirdly ask the user to enter several letters then find all the words that can be made with those lettersrepeats allowed using the wordlistproduce dictionary whose keys are the letters through and whose values are the percentage of words that use that letter using the wordlistproduce dictionary whose keys are the letters through and whose values are the percentage of total letters in the wordlist that are that letter write program that asks the user for word and finds all the smaller words that can be made from the letters of that word the number of occurrences of letter in smaller word can' exceed the number of occurrences of the letter in the user' word (awrite program that reads file consisting of email addresseseach on its own line your program should print out string consisting of those email addresses separated by semicolons (bwrite the same program as abovebut the new string should contain only those email addresses that do not end in @prof college edu
9,272
the file high_temperatures txt contains the average high temperatures for each day of the year in certain city each line of the file consists of the datewritten in the month/day formatfollowed by space and the average high temperature for that date find the -day period over which there is the biggest increase in the average high temperature in there was an exercise about the game mad libs it asked you to make up story and leave out some words of the story your program should ask the user to enter some words and tell them what types of words to enter then print the full story along with the inserted words rewrite your program from that exercise to read the story from file reading the story from file allows people who do not know how to program to use their own stories with the program without having to change the code an acronym is an abbreviation that uses the first letter of each word in phrase we see them everywhere for instancencaa for national collegiate athletic association or nbc for national broadcasting company write program where the user enters an acronym and the program randomly selects words from wordlist such that the words would fit the acronym below is some typical output generated when ran the programenter acronymabc ['addressed''better''common'enter acronymbrian ['bank''regarding''intending''army''naive' this problem is about version of the game jotto the computer chooses random five-letter word with no repeat letters the player gets several turns to try to guess the computer' word on each turnthe player guesses five-letter word and is told the number of letters that their guess has in common with the computer' word the word part has the interesting property that if you remove its letters one by oneeach resulting step is real word for instancepart pat pa you may remove the letters in any orderand the last (single-letterword needs to be real word as well find all eight-letter words with this property write program to cheat at the game scrabble the user enters string your program should return list of all the words that can be created from those seven letters
9,273
text files
9,274
functions functions are useful for breaking up large program to make it easier to read and maintain they are also useful if you find yourself writing the same code at several different points in your program you can put that code in function and call the function whenever you want to execute that code you can also use functions to create your own utilitiesmath functionsetc basics functions are defined with the def statement the statement ends with colonand the code that is part of the function is indented below the def statement here we create simple function that just prints something def print_hello()print'hello'print_hello(print' 'print_hello(hello hellothe first two lines define the function in the last three lines we call the function twice one use for functions is if you are using the same code over and over again in various parts of your programyou can make your program shorter and easier to understand by putting the code in function for instancesuppose for some reason you need to print box of stars like the one below at several points in your program
9,275
functions **************************put the code into functionand then whenever you need boxjust call the function rather than typing several lines of redundant code here is the function def draw_square()print' print'''* ''print'''* ''print' one benefit of this is that if you decide to change the size of the boxyou just have to modify the code in the functionwhereas if you had copied and pasted the box-drawing code everywhere you needed ityou would have to change all of them arguments we can pass values to functions here is an exampledef print_hello( )print'hello nprint(print_hello( print_hello( times print_hello(timeshello hello hello hello hello hello hello hello hello hello when we call the print_hello function with the value that value gets stored in the variable we can then refer to that variable in our function' code you can pass more than one value to functiondef multiple_print(stringn)print(string nprint(multiple_print'hello ' multiple_print' '
9,276
hellohellohellohellohello aaaaaaaaaa returning values we can write functions that perform calculations and return result example here is simple function that converts temperatures from celsius to fahrenheit def convert( )return * / + print(convert( ) the return statement is used to send the result of function' calculations back to the caller notice that the function itself does not do any printing the printing is done outside of the function that waywe can do math with the resultlike below print(convert( )+ if we had just printed the result in the function instead of returning itthe result would have been printed to the screen and forgotten aboutand we would never be able to do anything with it example as another examplethe python math module contains trig functionsbut they only work in radians let us write our own sine function that works in degrees from math import pisin def deg_sin( )return sin(pi* / example function can return multiple values as list say we want to write function that solves the system of equations ax and it turns out that if there is unique solutionthen it is given by (de )/(ad bcand ( ce)/(ad bcwe need our function to return both the and solutions def solve( , , , , , ) ( * - * )/( * - *cy ( * - * )/( * - *creturn [ ,
9,277
functions xsolysol solve( , , , , , print'the solution is 'xsol'and 'ysolthe solution is and - this method uses the shortcut for assigning to lists that was mentioned in section example return statement by itself can be used to end function early def multiple_print(stringnbad_words)if string in bad_wordsreturn print(string nprint(the same effect can be achieved with an if/else statementbut in some casesusing return can make your code simpler and more readable default arguments and keyword arguments you can specify default value for an argument this makes it optionaland if the caller decides not to use itthen it takes the default value here is an exampledef multiple_print(stringn= print(string nprint(multiple_print'hello ' multiple_print'hello 'hellohellohellohellohello hello default arguments need to come at the end of the function definitionafter all of the non-default arguments keyword arguments related concept to default arguments is keyword arguments say we have the following function definitiondef fancy_print(textcolorbackgroundstylejustify)every time you call this functionyou have to remember the correct order of the arguments fortunatelypython allows you to name the arguments when calling the functionas shown belowfancy_print(text'hi 'color'yellow 'background'black 'style'bold 'justify'left '
9,278
fancy_print(text'hi 'style'bold 'justify'left 'background'black 'color'yellow 'as we can seethe order of the arguments does not matter when you use keyword arguments when defining the functionit would be good idea to give defaults for instancemost of the timethe caller would want left justificationa white backgroundetc using these values as defaults means the caller does not have to specify every single argument every time they call the function here is exampledef fancy_print(textcolor'black 'background'white 'style'normal 'justify'left ')function code goes here fancy_print'hi 'style'bold 'fancy_print'hi 'color'yellow 'background'black 'fancy_print'hi 'note we have actually seen default and keyword arguments before--the sepend and file arguments of the print function local variables let' say we have two functions like the ones below that each use variable idef func ()for in range( )print(idef func () = func (print(ia problem that could arise here is that when we call func we might mess up the value of in func in large program it would be nightmare trying to make sure that we don' repeat variable names in different functionsandfortunatelywe don' have to worry about this when variable is defined inside functionit is local to that functionwhich means it essentially does not exist outside that function this way each function can define its own variables and not have to worry about if those variable names are used in other functions global variables on the other handsometimes you actually do want the same variable to be available to multiple functions such variable is called global variable you have to be careful using global variablesespecially in larger programsbut few global variables used judiciously are fine in smaller programs here is short example
9,279
functions def reset()global time_left time_left def print_time()print(time_lefttime_left= in this program we have variable time_left that we would like multiple functions to have access to if function wants to change the value of that variablewe need to tell the function that time_left is global variable we use global statement in the function to do this on the other handif we just want to use the value of the global variablewe do not need global statement arguments we finish the with bit of technical detail you can skip this section for the time being if you don' want to worry about details right now here are two simple functionsdef func ( ) def func ( ) [ = =[ , , func (afunc (mwhen we call func with and func with la question arisesdo the functions change the values of and lthe answer may surprise you the value of is unchangedbut the value of is changed the reason has to do with difference in the way that python handles numbers and lists lists are said to be mutable objectsmeaning they can be changedwhereas numbers and strings are immutablemeaning they cannot be changed there is more on this in section if we want to reverse the behavior of the above example so that is modified and is notdo the followingdef func ( ) return def func ( )copy [:copy copy [ = =[ , , =func (anote change on this line
9,280
func ( exercises write function called rectangle that takes two integers and as arguments and prints out an box consisting of asterisks shown below is the output of rectangle( , ****** (awrite function called add_excitement that takes list of strings and adds an exclamation point (!to the end of each string in the list the program should modify the original list and not return anything (bwrite the same function except that it should not modify the original list and should instead return new list write function called sum_digits that is given an integer num and returns the sum of the digits of num the digital root of number is obtained as followsadd up the digits to get new number add up the digits of that to get another new number keep doing this until you get number that has only one digit that number is the digital root for exampleif we add up the digits to get we then add up the digits of to get we then add up the digits of to get since has only one digit is our digital root write function that returns the digital root of an integer [notethere is shortcutwhere the digital root is equal to mod but do not use that here write function called first_diff that is given two strings and returns the first location in which the strings differ if the strings are identicalit should return - write function called binomthat takes two integers and and returns the binomial coefnficient nk the definition is nk !( - ) write function that takes an integer and returns random integer with exactly digits for instanceif is then and would be valid return valuesbut would not because that is really which is two-digit number write function called number_of_factors that takes an integer and returns how many factors the number has write function called factors that takes an integer and returns list of its factors write function called closest that takes list of numbers and number and returns the largest element in that is not larger than for instanceif =[ , , , , and = then the function should return because is the closest thing in to that is not larger than don' worry about if all of the things in are smaller than
9,281
functions write function called matches that takes two strings as arguments and returns how many matches there are between the strings match is where the two strings have the same character at the same index for instance'pythonand 'pathmatch in the firstthirdand fourth charactersso the function should return recall that if is stringthen find(' 'will find the location of the first in the problem is that it does not find the location of every write function called findall that given string and single characterreturns list containing all of the locations of that character in the string it should return an empty list if there are no occurrences of the character in the string write function called change_case that given stringreturns string with each upper case letter replaced by lower case letter and vice-versa write function called is_sorted that is given list and returns true if the list is sorted and false otherwise write function called root that is given number and an integer and returns / in the function definitionset the default value of to write function called one_away that takes two strings and returns true if the strings are of the same length and differ in exactly one letterlike bike/hike or water/wafer (awrite function called primes that is given number and returns list of the first primes let the default value of be (bmodify the function above so that there is an optional argument called start that allows the list to start at value other than the function should return the first primes that are greater than or equal to start the default value of start should be our number system is called base because we have ten digits some culturesincluding the mayans and celtsused base system in one version of this systemthe digits are represented by the letters through here is table showing few conversions ba bb bc bd bt ca cb da tt baa bab bac write function called base that converts base number to base it should return the result as string of base digits one way to convert is to find the remainder when the number is divided by then divide the number by and repeat the process until the number is the remainders are the base digits in reverse orderthough you have to convert them into their letter equivalents
9,282
write function called verbose thatgiven an integer less than returns the name of the integer in english as an exampleverbose( should return one hundred twenty-three thousandfour hundred fifty-six write function called merge that takes two already sorted lists of possibly different lengthsand merges them into single sorted list (ado this using the sort method (bdo this without using the sort method in the way we checked to see if word was real word wasif in wordswhere words was the list of words generated from wordlist this is unfortunately slowbut there is faster waycalled binary search to implement binary search in functionstart by comparing with the middle entry in words if they are equalthen you are done and the function should return true on the other handif comes before the middle entrythen search the first half of the list if it comes after the middle entrythen search the second half of the list then repeat the process on the appropriate half of the list and continue until the word is found or there is nothing left to searchin which case the function short return false the operators can be used to alphabetically compare two strings tic-tac-toe board can be represented be two-dimensional listwhere zeroes stand for empty cellsones stand for ' and twos stand for ' (awrite function that is given such list and randomly chooses spot in which to place the spot chosen must currently be and spot must be chosen (bwrite function that is given such list and checks to see if someone has won return true if there is winner and false otherwise write function that is given potentially solved sudoku and returns true if it is solved correctly and false if there is mistake the sudoku is correctly solved if there are no repeated numbers in any row or any column or in any of the nine "blocks
9,283
functions
9,284
object-oriented programming about year or so after started programmingi decided to make game to play wheel of fortune wrote the program in the basic programming language and it got to be pretty largea couple thousand lines it mostly workedbut whenever tried to fix somethingmy fix would break something in completely different part of the program would then fix that and break something else eventually got the program workingbut after while was afraid to even touch it the problem with the program was that each part of the program had access to the variables from the other parts change of variable in one part would mess up things in the others one solution to this type of problem is object-oriented programming one of its chief benefits is encapsulationwhere you divide your program into pieces and each piece internally operates independently of the others the pieces interact with each otherbut they don' need to know exactly how each one accomplishes its tasks this requires some planning and set-up time before you start your programand so it is not always appropriate for short programslike many of the ones that we have written so far we will just cover the basics of object-oriented programming here object-oriented programming is used extensively in software design and would recommend picking up another book on programming or software design to learn more about designing programs in an object-oriented way python is objected-oriented python is an object-oriented programming languageand we have in fact been using many objectoriented concepts already the key notion is that of an object an object consists of two thingsdata and functions (called methodsthat work with that data as an examplestrings in python are objects the data of the string object is the actual characters that make up that string the methods are things like lowerreplaceand split in pythoneverything is an object that includes not only strings and listsbut also integersfloatsand even functions themselves
9,285
object-oriented programming creating your own classes class is template for objects it contains the code for all the object' methods simple example here is simple example to demonstrate what class looks like it does not do anything interesting class exampledef __init__(selfab)self self def add(self)return self self example( print( add()to create classwe use the class statement class names usually start with capital most classes will have method called __init__ the underscores indicate that it is special kind of method it is called constructorand it is automatically called when someone creates new object from your class the constructor is usually used to set up the class' variables in the above programthe constructor takes two valuesa and band assigns the class variables and to those values the first argument to every method in your class is special variable called self every time your class refers to one of its variables or methodsit must precede them by self the purpose of self is to distinguish your class' variables and methods from other variables and functions in the program to create new object from the classyou call the class name along with any values that you want to send to the constructor you will usually want to assign it to variable name this is what the line =example( , does to use the object' methodsuse the dot operatoras in addmod( more practical example here is class called analyzer that performs some simple analysis on string there are methods to return how many words are in the stringhow many are of given lengthand how many start with given string from string import punctuation class analyzerdef __init__(selfs)for in punctuations replace( ''
9,286
lower(self words split(def number_of_words(self)return len(self wordsdef starts_with(selfs)return len([ for in self words if [:len( )]== ]def number_with_length(selfn)return len([ for in self words if len( )== ] 'this is test of the class analyzer analyzer(sprint(analyzer wordsprint'number of words'analyzer number_of_words()print'number of words starting with " "'analyzer starts_with' ')print'number of -letter words'analyzer number_with_length( )['this''is'' ''test''of''the''class'number of words number of words starting with " " number of -letter words few notes about this programone reason why we would wrap this code up in class is we can then use it variety of different programs it is also good just for organizing things if all our program is doing is just analyzing some stringsthen there' not too much of point of writing classbut if this were to be part of larger programthen using class provides nice way to separate the analyzer code from the rest of the code it also means that if we were to change the internals of the analyzer classthe rest of the program would not be affected as long as the interfacethe way the rest of the program interacts with the classdoes not change alsothe analyzer class can be imported as-is in other programs the following line accesses class variableprint(analyzer wordsyou can also change class variables this is not always good thing in some cases this is convenientbut you have to be careful with it indiscriminate use of class variables goes against the idea of encapsulation and can lead to programming errors that are hard to fix some other object-oriented programming languages have notion of public and private variablespublic variables being those that anyone can access and changeand private variables being only accessible to methods within the class in python all variables are publicand it is up to the programmer to be responsible with them there is convention where you name those variables that you want to be private with starting underscorelike _var this serves to let others know that this variable is internal to the class and shouldn' be touched
9,287
object-oriented programming inheritance in object-oriented programming there is concept called inheritance where you can create class that builds off of another class when you do thisthe new class gets all of the variables and methods of the class it is inheriting from (called the base classit can then define additional variables and methods that are not present in the base classand it can also override some of the methods of the base class that isit can rewrite them to suit its own purposes here is simple exampleclass parentdef __init__(selfa)self def method (self)return self * def method (self)return self '!!class child(parent)def __init__(selfab)self self def method (self)return self * def method (self)return self self parent'hi ' child'hi ''bye 'print'parent method ' method ()print'parent method ' method ()print(print'child method ' method ()print'child method ' method ()print'child method ' method ()parent method hihi parent method hi!!child method hihihihihihihi child method hi!!child method hibye we see in the example above that the child has overridden the parent' method causing it to now repeat the string seven times the child has inherited the parent' method so it can use it without having to define it the child also adds some features to the parent classnamely new variable and new methodmethod note about syntaxwhen inheriting from classyou indicate the parent class in parentheses in the class statement
9,288
if the child class adds some new variablesit can call the parent class' constructor as demonstrated below another use is if the child class just wants to add on to one of the parent' methods in the example belowthe child' print_var method calls the parent' print_var method and adds an additional line class parentdef __init__(selfa)self def print_var(self)print("the value of this class ' variables are:"print(self aclass child(parent)def __init__(selfab)parent __init__(selfaself def print_var(self)parent print_var(selfprint(self bnote you can also inherit from python built-in typeslike strings (strand lists (list)as well as any classes defined in the various modules that come with python note your code can inherit from more than one class at timethough this can be little tricky playing-card example in this section we will show how to design program with classes we will create simple hi-lo card game where the user is given card and they have to say if the next card will be higher or lower than it this game could easily be done without classesbut we will create classes to represent card and deck of cardsand these classes can be reused in other card games we start with class for playing card the data associated with card consists of its value ( through and its suit the card class below has only one method__str__ this is special method thatamong other thingstells the print function how to print card object class carddef __init__(selfvaluesuit)self value value self suit suit def __str__(self)names 'jack ''queen ''king ''ace 'if self value <
9,289
object-oriented programming return '{of {format(self valueself suitelsereturn '{of {format(names[self value- ]self suitnext we have class to represent group of cards its data consists of list of card objects it has number of methodsnextcard which removes the first card from the list and returns ithascard which returns true or false depending on if there are any cards left in the listsizewhich returns how many cards are in the listand shufflewhich shuffles the list import random class card_groupdef __init__(selfcards=[])self cards cards def nextcard(self)return self cards pop( def hascard(self)return len(self cards)> def size(self)return len(self cardsdef shuffle(self)random shuffle(self cardswe have one more class standard_deckwhich inherits from card_group the idea here is that card_group represents an arbitrary group of cardsand standard_deck represents specific group of cardsnamely the standard deck of cards used in most card games class standard_deck(card_group)def __init__(self)self cards [for in 'hearts ''diamonds ''clubs ''spades ']for in range( , )self cards append(card(vs)suppose we had just created single class that represented standard deck along with all the common operations like shuffling if we wanted to create new class for pinochle game or some other game that doesn' use the standard deckthen we would have to copy and paste the standard deck code and modify lots of things by doing things more generallylike we've done hereeach time we want new type of deckwe can build off of (inherit fromwhat is in card_group for instancea pinochle deck class would look like thisclass pinochle_deck(card_group)def __init__(self)self cards [for in 'hearts ''diamonds ''clubs ''spades ']*
9,290
for in range( , )self cards append(card(vs) pinochle deck has only ninestensjacksqueenskingsand aces there are two copies of each card in each suit here is the hi-low program that uses the classes we have developed here one way to think of what we have done with the classes is that we have built up miniature card programming languagewhere we can think about how card game works and not have to worry about exactly how cards are shuffled or dealt or whateversince that is wrapped up into the classes for the hi-low gamewe get new deck of cardsshuffle itand then deal out the cards one at time when we run out of cardswe get new deck and shuffle it nice feature of this game is that it deals out all cards of deckso player can use their memory to help them play the game deck standard_deck(deck shuffle(new_card deck nextcard(print'\ 'new_cardchoice input("higher (hor lower ( )"streak while (choice=' or choice=' ')if not deck hascard()deck standard_deck(deck shuffle(old_card new_card new_card deck nextcard(if (choice lower()=' and new_card value>old_card value orchoice lower()=' and new_card value<old_card value)streak streak print("rightthat ' "streak"in row!"elif (choice lower()=' and new_card value<old_card value orchoice lower()=' and new_card value>old_card value)streak print'wrong 'elseprint'push 'print'\ 'new_cardchoice input("higher (hor lower ( )"king of clubs higher (hor lower ( ) rightthat' in row of spades
9,291
object-oriented programming higher (hor lower ( ) rightthat' in row tic-tac-toe example in this section we create an object-oriented tic-tac-toe game we use class to wrap up the logic of the game the class contains two variablesan integer representing the current playerand list representing the board the board variable consists of zerosonesand twos zeros represent an open spotwhile ones and twos represent spots marked by players and respectively there are four methodsget_open_spots -returns list of the places on the board that have not yet been marked by players is_valid_move -takes row and column representing potential moveand returns true if move is allowed and false otherwise make_move -takes row and column representing potential movecalls is_valid_move to see if the move is okayand if it issets the board array accordingly and changes the player check_for_winner -scans through the board list and returns if player has won if player has won if there are no moves remaining and no winnerand - if the game should continue here is the code for the classclass tic_tac_toedef __init__(self)self [[ , , ][ , , ][ , , ]self player def get_open_spots(self)return [[ ,cfor in range( for in range( if self [ ][ ]== def is_valid_move(self, , )if <= <= and <= <= and self [ ][ ]== return true return false def make_move(self, , )if self is_valid_move( , )self [ ][cself player self player (self player+ )% def check_for_winner(self)
9,292
for in range( )if self [ ][ ]==self [ ][ ]==self [ ][ ]!= return self [ ][cfor in range( )if self [ ][ ]==self [ ][ ]==self [ ][ ]!= return self [ ][ if self [ ][ ]==self [ ][ ]==self [ ][ ]!= return self [ ][ if self [ ][ ]==self [ ][ ]==self [ ][ ]!= return self [ ][ if self get_open_spots()==[]return return - this class consists of the logic of the game there is nothing in the class that is specific to the user interface below we have text-based interface using print and input statements if we decide to use graphical interfacewe can use the tic_tac_toe class without having to change anything about it note that the get_open_spots method is not used by this program it is usefulhoweverif you want to implement computer player simple computer player would call that method and use random choice method to choose random element from the returned list of spots def print_board()chars ''' '' 'for in range( )for in range( )print(chars[game [ ][ ]]end'print(game tic_tac_toe(while game check_for_winner()==- print_board( , eval(input'enter spotplayer str(game player'')game make_move( ,cprint_board( game check_for_winner(if == print("it ' draw "elseprint'player ' 'wins'here is what the first couple of turns look likeenter spotplayer ,
9,293
object-oriented programming enter spotplayer , enter spotplayer further topics special methods -we have seen two special methods alreadythe constructor __init__ and the method __str__ which determines what your objects look like when printed there are many others for instancethere is __add__ that allows your object to use the operator there are special methods for all the python operators there is also method called __len__ which allows your object to work with the built in len function there is even special method__getitem__ that lets your program work with list and string brackets [copying objects -if you want to make copy of an object xit is not enough to do the followingx_copy the reason is discussed in section insteaddo the followingfrom copy import copy x_copy copy(xkeeping your code in multiple files -if you want to reuse class in several programsyou do not have to copy and paste the code into each you can save it in file and use an import statement to import it into your programs the file will need to be somewhere your program can find itlike in the same directory from analyzer import analyzer exercises write class called investment with fields called principal and interest the constructor should set the values of those fields there should be method called value_after that returns the value of the investment after years the formula for this is ( ) where is the principaland is the interest rate it should also use the special method __str__ so that printing the object will result in something like belowprincipal $ interest rate write class called product the class should have fields called nameamountand priceholding the product' namethe number of items of that product in stockand the regular price of the product there should be method get_price that receives the number of items to be bought and returns the cost of buying that many itemswhere the regular price
9,294
is charged for orders of less than itemsa discount is applied for orders of between and itemsand discount is applied for orders of or more items there should also be method called make_purchase that receives the number of items to be bought and decreases amount by that much write class called password_manager the class should have list called old_passwords that holds all of the user' past passwords the last item of the list is the user' current password there should be method called get_password that returns the current password and method called set_password that sets the user' password the set_password method should only change the password if the attempted password is different from all the user' past passwords finallycreate method called is_correct that receives string and returns boolean true or false depending on whether the string is equal to the current password or not write class called time whose only field is time in seconds it should have method called convert_to_minutes that returns string of minutes and seconds formatted as in the following exampleif seconds is the method should return ' : it should also have method called convert_to_hours that returns string of hoursminutesand seconds formatted analogously to the previous method write class called wordplay it should have field that holds list of words the user of the class should pass the list of words they want to use to the class there should be the following methodswords_with_length(length-returns list of all the words of length length starts_with( -returns list of all the words that start with ends_with( -returns list of all the words that end with palindromes(-returns list of all the palindromes in the list only( -returns list of the words that contain only those letters in avoids( -returns list of the words that contain none of the letters in write class called converter the user will pass length and unit when declaring an object from the class--for examplec converter( ,'inches'the possible units are inchesfeetyardsmileskilometersmeterscentimetersand millimeters for each of these units there should be method that returns the length converted into those units for exampleusing the converter object created abovethe user could call feet(and should get as the result use the standard_deck class of this section to create simplified version of the game war in this gamethere are two players each starts with half of deck the players each deal the top card from their decks and whoever has the higher card wins the other player' cards and adds them to the bottom of his deck if there is tiethe two cards are eliminated from play (this differs from the actual gamebut is simpler to programthe game ends when one player runs out of cards
9,295
object-oriented programming write class that inherits from the card_group class of this the class should represent deck of cards that contains only hearts and spaceswith only the cards through in each suit add method to the class called next that returns the top two cards from the deck write class called rock_paper_scissors that implements the logic of the game rockpaper-scissors for this game the user plays against the computer for certain number of rounds your class should have fields for the how many rounds there will bethe current round numberand the number of wins each player has there should be methods for getting the computer' choicefinding the winner of roundand checking to see if someone has one the (entiregame you may want more methods (awrite class called connect that implements the logic of connect game use the tic_tac_toe class from this as starting point (buse the connect class to create simple text-based version of the game write class called poker_hand that has field that is list of card objects there should be the following self-explanatory methodshas_royal_flushhas_straight_flushhas_four_of_a_kindhas_full_househas_flushhas_straighthas_three_of_a_kindhas_two_pairhas_pair there should also be method called best that returns string indicating what the best hand is that can be made from those cards
9,296
graphics
9,297
gui programming with tkinter up until nowthe only way our programs have been able to interact with the user is through keyboard input via the input statement but most real programs use windowsbuttonsscrollbarsand various other things these widgets are part of what is called graphical user interface or gui this is about gui programming in python with tkinter all of the widgets we will be looking at have far more options than we could possibly cover here an excellent reference is fredrik lundh' introduction to tkinter [ basics nearly every gui program we will write will contain the following three linesfrom tkinter import root tk(mainloop(the first line imports all of the gui stuff from the tkinter module the second line creates window on the screenwhich we call root the third line puts the program into what is essentially long-running while loop called the event loop this loop runswaiting for keypressesbutton clicksetc and it exits when the user closes the window here is working gui program that converts temperatures from fahrenheit to celsius from tkinter import def calculate()temp int(entry get()temp / *temp+ output_label configure(text 'converted{ fformat(temp)entry delete( ,end
9,298
gui programming with tkinter root tk(message_label label(text'enter temperature 'font='verdana ' )output_label label(font='verdana ' )entry entry(font='verdana ' )width= calc_button button(text'ok 'font='verdana ' )command=calculatemessage_label grid(row= column= entry grid(row= column= calc_button grid(row= column= output_label grid(row= column= columnspan= mainloop(here is what the program looks likewe now will examine the components of the program separately labels label is place for your program to place some text on the screen the following code creates label and places it on the screen hello_label label(text'hello 'hello_label grid(row= column= we call label to create new label the capital is required our label' name is hello_label once createduse the grid method to place the label on the screen we will explain grid in the next section options there are number of options you can change including font size and color here are some exampleshello_label label(text'hello 'font='verdana ' 'bold ')bg'blue 'fg'white 'note the use of keyword arguments here are few common optionsfont -the basic structure is font(font namefont sizestyleyou can leave out the font size or the style the choices for style are 'bold''italic''underline''overstrike''roman'and 'normal(which is the defaultyou can combine multiple styles like this'bold italic
9,299
fg and bg -these stand for foreground and background many common color names can be usedlike 'blue''green'etc section describes how to get essentially any color width -this is how many characters long the label should be if you leave this outtkinter will base the width off of the text you put in the label this can make for unpredictable resultsso it is good to decide ahead of time how long you want your label to be and set the width accordingly height -this is how many rows high the label should be you can use this for multiline labels use newline characters in the text to get it to span multiple lines for exampletext='hi\ntherethere are dozens more options the aforementioned introduction to tkinter [ has nice list of the others and what they do changing label properties later in your programafter you've created labelyou may want to change something about it to do thatuse its configure method here are two examples that change the properties of label called labellabel configure(text'bye 'label configure(bg'white 'fg'black 'setting text to something using the configure method is kind of like the gui equivalent of print statement howeverin calls to configure we cannot use commas to separate multiple things to print we instead need to use string formatting here is print statement and its equivalent using the configure method print' ' 'and 'blabel configure(text' {}and {format( , )the configure method works with most of the other widgets we will see grid the grid method is used to place things on the screen it lays out the screen as rectangular grid of rows and columns the first few rows and columns are shown below (row= column= (row= column= (row= column= (row= column= (row= column= (row= column= (row= column= (row= column= (row= column= spanning multiple rows or columns there are optional argumentsrowspan and columnspanthat allow widget to take up more than one row or column here is an example of several grid statements followed by what the layout will look like