Quiz3 Practice FitBs


These problems are provided to give you optional practice on the FitB style questions that will be on Quiz3.
Practice-FitB1
Fill in the blank so f(s) == g(s) for all strings s.
def f(s):
    if not s.isalpha():
        return ''
    d = None
    for c in s:
        e = abs(ord(c) - ord('D'))
        if (d == None) or (e < d):
            d = e
    return d == 0

def g(s):
    if not s.isalpha():
        return ''
    return _____________
Answer:

'D' in s


Practice-FitB2
Fill in the blank so f(s) == g(s) for all strings s.
def f(s):
    if not s.isalpha():
        return ''
    while (len(s) >= 2) and (s[0] == s[-1]):
        s = s[1:-1]
    return len(s) < 2

def g(s):
    if not s.isalpha():
        return ''
    return _____________
Answer:

s == s[::-1]


Practice-FitB3
Fill in the blank so f(s) == g(s) for all strings s.
import string

def f(s):
    if not s.isalpha():
        return ''
    t = s
    for c in string.ascii_uppercase:
        t = t.replace(c, '')
    return t == s

def g(s):
    if not s.isalpha():
        return ''
    return _____________
Answer:

s.islower()


Practice-FitB4
Fill in the blank so f(s) == g(s) for all strings s.
import string

# This is a helper function for f(s):
def h(s, c):
    n = 0
    for part in s.split(c):
        n += 1
    return n == 2

def f(s):
    if not s.isupper():
        return False
    for c in s:
        if not h(s, c):
            return False
    return True

def g(s):
    if not s.isupper():
        return False
    for c in string.ascii_uppercase:
        if _____________:
            return False
    return True
Answer:

s.count(c) > 1


Practice-FitB5
Fill in the blank so f(s) == g(s) for all strings s.
def f(s):
    if not s.isalpha():
        return False
    if len(s) % 2 != 0:
        return False
    for i in range(len(s)):
        if s[i] != s[i%2]:
            return False
    return True

def g(s):
    if not s.isalpha():
        return False
    return s == _____________
Answer:

s[:2] * (len(s)//2)