![]() |
![]() |
|
home—info—labs—exams—hws
—D2L—MediaSamples/—breeze (snow day)—tutor/PIs
Recall how we used loops, along with a “so-far” variable, to build up (say) multiple copies of a string, back in lab33—Accumulating an answer and lab34—loop practice: accumulating a string.
# stringTimes: int, string -> string # Return multiple copies of `txtToRepeat`. # Example: stringTimes( 3, "Koala" ) ⇒ "KoalaKoalaKoala" # def stringTimes( numCopies, txtToRepeat ): stringSoFar = "" # one-time setup for currentCopyNumber in range(numCopies): stringSoFar = stringSoFar + txtToTRepeat return stringSoFar |
We know that
pet = "wallaby" pet[1] pet[5] pet[6] pet[7] # ERROR! |
Accessing individual items by their index is powerful, when combined with arrays:
for i in range(8): printNow("I got me a " + pet + "; it has a " + pet[i] + "!") |
# substring : string, int, int → string # Given some text, a start-index, and a stop-index, # return the characters of `txt` from `start` up until (but not including) `stop`. # Indices are 0-based. # Examples: substring( "radford", 3, 6) = "for" # substring( "radford", 0, 3) = "rad" # def substring(txt, start, stop): if (0 <= start and start <= stop and stop <= len(txt)): resultSoFar = "" for i in range(stop-start): resultSoFar = resultSoFar + txt[start+i] return resultSoFar else: raise IndexError("substring: bounds out of range: " + str(start) + "," + str(stop) + " for '" + txt + "'") |
As a class, we'll write:
# countVowels: string -> int # Return the number of vowels in a string. # def test(): print( "Actual: " + str( countVowels( "a" ) ) ) print( "Expect: " + str(1) ) print( "Actual: " + str( countVowels( "b" ) ) ) print( "Expect: " + str(0) ) print( "Actual: " + str( countVowels( "" ) ) ) print( "Expect: " + str(0) ) print( "Actual: " + str( countVowels( "aa" ) ) ) print( "Expect: " + str(2) ) print( "Actual: " + str( countVowels( "ba" ) ) ) print( "Expect: " + str(1) ) print( "Actual: " + str( countVowels( "hello" ) ) ) print( "Expect: " + str(2) ) print( "Actual: " + str( countVowels( "abcde" ) ) ) print( "Expect: " + str(2) ) print( "Actual: " + str( countVowels( "zzzzz" ) ) ) print( "Expect: " + str(0) ) print( "Actual: " + str( countVowels( "zaeiouyAEIOUYzzzz" ) ) ) print( "Expect: " + str(12) ) |
YOUR TASK (part of next lab's problems):
Write a function
hint: As you write this, and you reach something which you wish was a built-in function, use the technique of wishful-thinking, and make up a helper-function to do what you want. Then you can come back later and write that, perhaps even getting some help.
1
In fact,
home—info—labs—exams—hws
—D2L—MediaSamples/—breeze (snow day)—tutor/PIs
©2014, Ian Barland, Radford University Last modified 2014.May.05 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarland ![]() |
![]() |