Function returns Function achieves Function does not the correct result progress toward achieve progress Algorithm the correct result toward the correct result Part IV: The best-so-far pattern When you want to find the best or worst of items in a list, use the best-so-far variable role. Best and worst can be the most or least of some quality that be compared. An example of the best-so-far pattern is given in the following code. Note the docstring. def 1 longest_word(words): 2 '''words is a list of strings 3 4 Returns the length of the longest word. 5 ''' most_letters = 0 6 for in 7 word words: most_letters: 8 if len(word) > most_letters = len(word) 9 10 return most_letters Execute the code above. Then call the function from the IPython session as shown below. In []: phrase = ['This', 'sentence', 'is', 'short.'] In []: longest_word(phrase) Out[]: 8 As a class, work together to explain how the code produces the output shown. Describe the function using human language. longest_word The variable is playing the best-so-far-role. Lines 6, 8, 9, most_letters and 10 each use this variable. The following four comments match the four lines, but the comments are not in order. Place each comment with the correct line in the table below. # Test whether the record has been broken. # Initialize to a value that is definitely less than the record. # Set the new record. # Use the best-of-all result. Code Comment Line 6: most_letters = 0
Algorithm Function returns the correct result Function achieves progress toward the correct result Function does not achieve progress toward the correct result Part IV: The best-so-far pattern When you want to find the best or worst of items in a list, use the best-so-far variable role. Best and worst can be the most or least of some quality that be compared. An example of the best-so-far pattern is given in the following code. Note the docstring. 1 2 3 4 5 6 7 8 9 10 def longest_word(words): '''words is a list of strings Returns the length of the longest word. ''' most_letters = 0 for word in words: if len(word) > most_letters: most_letters = len(word) return most_letters Execute the code above. Then call the function from the IPython session as shown below. In []: In []: Out[]: phrase = ['This', 'sentence', 'is', 'short.'] longest_word(phrase) 8 As a class, work together to explain how the code produces the output shown. Describe the longest_word function using human language. The variable most_letters is playing the best-so-far-role. Lines 6, 8, 9, and 10 each use this variable. The following four comments match the four lines, but the comments are not in order. Place each comment with the correct line in the table below. # Test whether the record has been broken. # Initialize to a value that is definitely less than the record. # Set the new record. # Use the best-of-all result. Code Comment Line 6: most_letters = 0
2.2.5.A%20LoopingPatterns.docx