Solution Files

You can find the solutions in the hw01.py and quiz01.py files.

Homework Questions

For this set of problems, you must run ok from within the problems directory. Remember that you may choose to work with a partner on homework questions.

Question 1

Fill in the blanks in the following function definition for adding a to the absolute value of b, without calling abs.

from operator import add, sub

def a_plus_abs_b(a, b):
    """Return a+abs(b), but without calling abs.

    >>> a_plus_abs_b(2, 3)
    5
    >>> a_plus_abs_b(2, -3)
    5
    """
    if b < 0:
f = sub
else:
f = add
return f(a, b)

Use OK to test your code:

python3 ok -q a_plus_abs_b

We choose the operator add or sub based on the sign of b.

Question 2

Write a function that takes three positive numbers and returns the sum of the squares of the two largest numbers. Use only a single line for the body of the function.

def two_of_three(a, b, c):
    """Return x*x + y*y, where x and y are the two largest members of the
    positive numbers a, b, and c.

    >>> two_of_three(1, 2, 3)
    13
    >>> two_of_three(5, 3, 1)
    34
    >>> two_of_three(10, 2, 8)
    164
    >>> two_of_three(5, 5, 5)
    50
    """
return max(a*a+b*b, a*a+c*c, b*b+c*c) return a**2 + b**2 + c**2 - min(a, b, c)**2

Use OK to test your code:

python3 ok -q two_of_three

We use the fact that if a>b and b>0, then square(a)>square(b). So, we can take the max of the sum of squares of all pairs. The max function can take an arbitrary number of arguments.

Question 3

Write a function that takes an integer n that is greater than 1 and returns the largest integer that is smaller than n and evenly divides n.

def largest_factor(n):
    """Return the largest factor of n that is smaller than n.

    >>> largest_factor(15) # factors are 1, 3, 5
    5
    >>> largest_factor(80) # factors are 1, 2, 4, 5, 8, 10, 16, 20, 40
    40
    >>> largest_factor(13) # factor is 1 since 13 is prime
    1
    """
factor = n - 1 while factor > 0: if n % factor == 0: return factor factor -= 1

Hint: To check if b evenly divides a, you can use the expression a % b == 0, which can be read as, "the remainder of dividing a by b is 0."

Use OK to test your code:

python3 ok -q largest_factor

Iterating from n-1 to 1, we return the first integer that evenly divides n. This is guaranteed to be the largest factor of n.

Question 4

Let's write a function that does the same thing as an if statement.

def if_function(condition, true_result, false_result):
    """Return true_result if condition is a true value, and
    false_result otherwise.

    >>> if_function(True, 2, 3)
    2
    >>> if_function(False, 2, 3)
    3
    >>> if_function(3==2, 3+2, 3-2)
    1
    >>> if_function(3>2, 3+2, 3-2)
    5
    """
    if condition:
        return true_result
    else:
        return false_result

Despite the doctests above, this function actually does not do the same thing as an if statement in all cases. To prove this fact, write functions c, t, and f such that with_if_statement returns the number 1, but with_if_function does not (it can do anything else):

def with_if_statement():
    """
    >>> with_if_statement()
    1
    """
    if c():
        return t()
    else:
        return f()

def with_if_function():
    return if_function(c(), t(), f())

def c():
return False
def t():
1/0
def f():
return 1

To test your solution, open an interactive interpreter

python3 -i hw01.py

and try calling with_if_function and with_if_statement to check that one returns 1 and the other doesn't.

Hint: If you are having a hard time identifying how the if statement and if function differ, first try to get them to print out different values.

The function with_if_function uses a call expression, which guarantees that all of its operand subexpressions will be evaluated before if_function is applied to the resulting arguments. Therefore, even if c returns False, the function t will be called. By contrast, with_if_statement will never call t if c returns False.

Question 5

Douglas Hofstadter's Pulitzer-prize-winning book, Gödel, Escher, Bach, poses the following mathematical puzzle.

  1. Pick a positive integer n as the start.
  2. If n is even, divide it by 2.
  3. If n is odd, multiply it by 3 and add 1.
  4. Continue this process until n is 1.

The number n will travel up and down but eventually end at 1 (at least for all numbers that have ever been tried -- nobody has ever proved that the sequence will terminate). Analogously, a hailstone travels up and down in the atmosphere before eventually landing on earth.

This sequence of values of n is often called a Hailstone sequence, Write a function that takes a single argument with formal parameter name n, prints out the hailstone sequence starting at n, and returns the number of steps in the sequence:

def hailstone(n):
    """Print the hailstone sequence starting at n and return its
    length.

    >>> a = hailstone(10)
    10
    5
    16
    8
    4
    2
    1
    >>> a
    7
    """
length = 1 while n != 1: print(n) if n % 2 == 0: n = n // 2 # Integer division prevents "1.0" output else: n = 3 * n + 1 length = length + 1 print(n) # n is now 1 return length

Hailstone sequences can get quite long! Try 27. What's the longest you can find?

Use OK to test your code:

python3 ok -q hailstone

Quiz Questions

For this set of problems, you must run ok from within the quiz directory. While homework questions may be completed with a partner, please remember that quiz questions must be completed alone.

Question 6: Multiple

Write a function that takes in two numbers and returns the smallest number that is a multiple of both.
def multiple(a, b):
    """Return the smallest number n that is a multiple of both a and b.

    >>> multiple(3, 4)
    12
    >>> multiple(14, 21)
    42
    """
n = 1 while True: if n % a == 0 and n % b == 0: return n n += 1

Use OK to test your code:

python3 ok -q multiple

Question 7: Unique Digits

Write a function that returns the number of unique digits in a positive integer.
def unique_digits(n):
    """Return the number of unique digits in positive integer n

    >>> unique_digits(8675309) # All are unique
    7
    >>> unique_digits(1313131) # 1 and 3
    2
    >>> unique_digits(13173131) # 1, 3, and 7
    3
    >>> unique_digits(10000) # 0 and 1
    2
    >>> unique_digits(101) # 0 and 1
    2
    >>> unique_digits(10) # 0 and 1
    2
    """
unique = 0 while n > 0: last, n = n % 10, n // 10 if not has_digit(n, last): unique += 1 return unique # unique = 0 # i = 0 # while i < 10: # if has_digit(n, i): # unique += 1 # i += 1 # return unique def has_digit(n, k): while n > 0: last, n = n % 10, n // 10 if last == k: return True return False

Hint: You may find it helpful to first define a function has_digit(n, k), which determines whether a number n has digit k.

Use OK to test your code:

python3 ok -q unique_digits

We have provided two solutions:

  • In one solution, we look at the current digit, and check if the rest of the number contains that digit or not. We only say it's unique if the digit doesn't exist in the rest. We do this for every digit.
  • In the other, we loop through the numbers 0-9 and just call has_digit on each one. If it returns true then we know the entire number contains that digit and we can one to our unique count.