CS140-lecture-20210915

Recursion #

image_2021-09-15-15-47-19 image_2021-09-15-15-48-02 image_2021-09-15-15-48-49 image_2021-09-15-15-50-21 image_2021-09-15-15-51-29 image_2021-09-15-15-54-34

Recursive tracing #

image_2021-09-15-15-55-20

m(648)
    m(72)
        m(9)
        return 9

image_2021-09-15-15-58-35 image_2021-09-15-15-59-23

My trace

m(348)
    a = m(34)
        a = m(3)
            return 33
        a = 33
        b = m(4)
            return 44
        b = 44
        return 3344
    a = 3344
    b = m(8)
        return 88
    b = 88
    return 334488

image_2021-09-15-16-07-17

pow example #

image_2021-09-15-16-08-14

My solution

pow(b, e):
    if e == 0:
        return 1
    return b * pow(b, e - 1)

Trace

pow(3, 4)
    3 * pow(3, 3)
        3 * pow(3, 2)
            3 * pow(3, 1)
                3 * pow(3, 0)
                    return 1
                3 * 1
                return 3
            3 * 3
            return 9
        3 * 9
        return 27
    3 * 27
    return 81
81

image_2021-09-15-16-16-56

The runtime of this is \( T(n) = T(n - 1) + 1 \) , so this is \( \Theta (n) \) .

image_2021-09-15-17-19-59

The runtime of the optimized verion is \[\begin{aligned} T(2n) &= T(n) + 1 \\ T(2n + 1) &= T(2n) + 1 \end{aligned}\] which results in a runtime complexity of \( \Theta (\lg n) \)

pow(m, n):
    if n == 0
        return 1
    else if n % 2 == 0
        tmp = pow(m, n/2)
        return tmp * tmp
    else
        return m * pow(m, n - 1)

image_2021-09-15-17-26-57

printBinary example #

image_2021-09-15-17-29-36

My solution in Python
def print_binary(n):

    def _print_binary(n, out):
        if n == 0:
            print(out)
            return
        elif n % 2 == 0:
            out = "0" + out
        else:
            out = "1" + out
        _print_binary(n // 2, out)

    _print_binary(n, "")


if __name__ == '__main__':
    print_binary(42)

Output

101010

image_2021-09-15-19-46-09 image_2021-09-15-19-46-12 image_2021-09-15-19-47-34

isPalindrome exercise #

image_2021-09-15-19-47-58

My solution in Python
def isPalindrome(s):
    if len(s) == 0 or len(s) == 1:
        return True
    elif s[0] == s[-1]:
        return isPalindrome(s[1:-1])
    else:
        return False

if __name__ == '__main__':
    print(isPalindrome("madam"))
    print(isPalindrome("racecar"))
    print(isPalindrome("step on no pets"))
    print(isPalindrome("able was I ere I saw elba"))
    print(isPalindrome("Java"))
    print(isPalindrome("rotater"))
    print(isPalindrome("byebye"))

Output

True
True
True
True
False
False
False

Public/private pairs #

image_2021-09-15-19-48-43