Solutions to strings HW06:
Remember to use helper functions: we can use isVowel in both countVowels and justTheVowels to shorten and clarify our code a lot.
#-----------------------
def countLetter(text, letter):
count = 0
for i in range(len(text)):
if text[i] == letter:
count += 1
return count
#-----------------------
def findLetter(A, B):
for i in range(len(A)):
if A[i] == B: #If found character
return i #Immediately done
#If we finished loop w/o returning,
#then B wasn't in the string
return -1
#-----------------------
def backwards(A):
s = ""
for i in range(len(A)-1, -1, -1): #loops from: len()-1, down to 0, (excluding -1)
s += A[i]
return s
#-----------------------
def emphasize(text):
s = ""
for i in range(len(text)):
if text[i] == ".":
s += "!"
else:
s += text[i]
return s
#-----------------------
# Three ways to write isVowel
def isVowel(c):
isLowerV = (c == "a" or c == "e" or c == "i" or c == "o" or c == "u" or c == "y")
isUpperV = (c == "A" or c == "E" or c == "I" or c == "O" or c == "U" or c == "Y")
return isLowerV or isUpperV #could also do it all in one long line, but I like splitting it
def isVowel2(c): #Less repetitive
vowels = "AEIOUYaeiouy"
for i in range(len(vowels)):
if vowels[i] == c:
return True
return False
def isVowel3(c): # Least repetitive, use findletter to do same check
return findLetter("AEIOUYaeiouy", c) != -1
#-----------------------
# Note: this is an excellent place to re-use the isVowel helper function
# It's both easier to write, and easier to read/understand your own code
def justTheVowels(text):
s = ""
for i in range(len(text)):
if isVowel(text[i]):
s += text[i]
return s
#-----------------------
def everyOther(A, startAt):
s = ""
for i in range(startAt, len(A), 2):
s += A[i]
return s