Skip to content

A Plus Abs B

python
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
    >>> a_plus_abs_b(-1, 4)
    3
    >>> a_plus_abs_b(-1, -4)
    3
    """
    if b < 0:
        f = sub
    else:
        f = add
    return f(a, b)

Two of Three

python

def two_of_three(i, j, k):
    """Return m*m + n*n, where m and n are the two smallest members of the
    positive numbers i, j, and k.

    >>> two_of_three(1, 2, 3)
    5
    >>> two_of_three(5, 3, 1)
    10
    >>> two_of_three(10, 2, 8)
    68
    >>> two_of_three(5, 5, 5)
    50
    """
    return (i + j + k + min(-i, -j, -k) + max(-i, -j, -k)) * (i + j + k + min(-i, -j, -k) + max(-i, -j, -k)) + min(i, j, k) * min(i, j, k)

Solution

python
	return x**2 + y**2 + z**2 - max(x, y, z)**2

Largest Factor

python
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
    """
    "*** YOUR CODE HERE ***"
    for a in range(n-1,0,-1):
        if(n % a == 0):
            break
    return a

Hailstone

python
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
    >>> b = hailstone(1)
    1
    >>> b
    1
    """
    "*** YOUR CODE HERE ***"
    print(n)
    hailstone.num = 0
    def calc_hailstone(n):
        hailstone.num += 1
        if(n % 2 == 0):
            n = n // 2
            print(n)
            calc_hailstone(n)
        else:
            if(n != 1):
                n = n * 3 + 1
                print(n)
                calc_hailstone(n)
    calc_hailstone(n)
    return hailstone.num

Solution

python
def hailstone(n):
    step = 1
    while x != 1:
        print(x)
        if x % 2 == 0:
            x //= 2
        else:
            x = 3*x + 1
        step += 1
    print(1)
    return step