Answers to string exercises (using for and range)

Main point: you can use helper functions (in particular, we use the findLetter() function a lot here) if you include that helper function in the CodingBat window.

# CodingBat homework

# ---------------------------------
def countLetter(string,letter):
  count = 0
  for i in range(len(string)):
    if string[i] == letter:
      count += 1
  return count
# ----------------------------------
# we can use the helper function findLetter() here, so
# we just define it below countVowels()

def countVowels(s):
  vowels = 'aeiouAEIOU'
  count = 0
  for i in range(len(s)):
    if findLetter(vowels,s[i]) >= 0:
      count += 1
  return count
  
def findLetter(string,letter):
  for i in range(len(string)):
    if string[i] == letter:
      return i
  return -1

# ------------------------------------
def isConsonant(c):
    lower = 'abcdefghijklmnopqrstuvwxyz'
    upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    vowels = 'aeiouAEIOU'
    # test if the character is a letter:
    if findLetter(lower,c) >= 0 or findLetter(upper,c) >= 0:
        # and if so, is it not a vowel?
        if findLetter(vowels,c) < 0:
            return True
    return False

# ---------------------------------------
def countWord(original,word):
    ln = len(word)
    count = 0
    for i in range(len(original)):
        if original[i:i+ln] == word:
            count += 1
    return count

# ---------------------------------
def noVowels(s):
    answer = ''
    vowels = 'aeiouAEIOU'
    for i in range(len(s)):
        if findLetter(vowels,s[i]) < 0:
            answer += s[i]
    return answer