Quiz2 Practice FitBs


These problems are provided to give you optional practice on the FitB style questions that will be on Quiz2.
Practice-FitB1
Fill in the blank so f(n) == g(n) for all integers n.
def f(n):
    n = abs(n)
    total = 0
    while n > 0:
        if n % 10 == 0:
            n //= 10
        else:
            n -= 1
            total += 1
    return total

def g(n):
    n = abs(n)
    total = 0
    while n > 0:
        total += __________________
        n //= 10
    return total
Answer:

n % 10


Practice-FitB2
Fill in the blank so f(n) == g(n) for all integers n.
def f(n):
    total = 0
    for k in range(n):
        if k >= n//2:
            break
        if k > 3 and k % 2 == 1:
            total += k
    return total

def g(n):
    total = 0
    for k in ___________________:
        total += k
    return total
Answer:

range(5, n//2, 2)


Practice-FitB3
Fill in the blank so f(n) == g(n) for all integers n.
def f(n):
    if n < 0:
        n = 0
    result = 0
    for x in range(n, -1, -1):
        result += x
    return result

def g(n):
    return ____________
Answer:

n*(n+1)//2 if n > 0 else 0


Practice-FitB4
Fill in the blank so f(n) == g(n) for all integers n.
def f(n):
    if n < 1:
        return 'out-of-range'
    result = 0
    x = 1
    while x <= n:
        result += 1
        x *= 10
    return result

def g(n):
    return _______________
Answer:

math.floor(1 + math.log10(n)) if n >= 1 else 'out-of-range'