CS 61A

Structure and Interpretation of Computer Programs, Spring 2015

Instructor: John DeNero




Question | Numbers Within

Write the function first_within, which takes in three numbers. Return whether the second number is contained within the first number and whether the third number is not contained within the first number. For a number to contain another, the digits have to appear contiguously, e.g. 102 contains 10 but not 12.

def first_within(whole, a, b):
    """
    >>> first_within(100, 10, 0)
    False
    >>> first_within(221, 21, 22)
    False
    >>> first_within(123, 23, 13)
    True
    >>> first_within(123, 0, 0)
    False
    """
    ## YOUR CODE HERE ##
def first_within(whole, a, b):
    return within(whole, a) and not within(whole, b)
def within(whole, a):
    if whole < 10:
        return a % 10 == whole
    if a < 10:
        return whole % 10 == a
    if a % 10 == whole % 10:
        return within(whole // 10, a // 10) or within(whole // 10, a)
    return within(whole // 10, a)