"""
CSCI 145 Day 6 - iteration (solutions)
"""


# ---------- Part 1: predict, then check ----------

# --- snippet A ---
x = 10
while x > 0:
    print(x)
    x = x - 3
# 10, 7, 4, 1

# --- snippet B ---
for i in range(4):
    print(i * 10)
# 0, 10, 20, 30

# --- snippet C ---
for i in range(2, 11, 4):
    print(i)
# 2, 6, 10

# --- snippet D ---
n = 5
while n < 5:
    print("inside the loop")
    n = n + 1
print("done")
# done (the condition is False the first time, so the body never runs)


# ---------- Part 2: write the code ----------

def countdown(n):
    """
    Use a while loop to print the numbers from n down to 1, one per
    line, and then print "Liftoff!".

    If n is 0 or negative, nothing is counted down: only "Liftoff!"
    is printed. Otherwise, n, n - 1, ..., 1 are printed first, and
    then "Liftoff!".

    Params: n (int) -- the number to count down from
    Returns: None
    """
    while n > 0:
        print(n)
        n -= 1
    print("Liftoff!")


def print_multiples(k, limit):
    """
    Use a for loop and range to print the multiples of k, one per line,
    starting at k and going up to limit.

    If limit is itself a multiple of k, limit is printed as the last
    number. Otherwise, the last number printed is the largest multiple
    of k that is less than limit.

    Params:
        k (int) -- the number to print multiples of (k >= 1)
        limit (int) -- the largest number that may be printed
    Returns: None
    """
    for i in range(k, limit + 1, k):
        print(i)


def print_powers_of_two(limit):
    """
    Bonus: print the powers of two (1, 2, 4, 8, 16, ...), one per line,
    as long as they are less than or equal to limit.

    If limit is less than 1, nothing is printed. Otherwise, the last
    number printed is the largest power of two that is <= limit.

    Params: limit (int) -- the largest number that may be printed
    Returns: None

    Think first: do you know in advance how many numbers you'll print?
    Which kind of loop fits best?
    """
    power = 1
    while power <= limit:
        print(power)
        power *= 2


print("countdown(3):")
countdown(3)          # 3, 2, 1, Liftoff!
print("countdown(0):")
countdown(0)          # Liftoff!

print("print_multiples(5, 20):")
print_multiples(5, 20)    # 5, 10, 15, 20
print("print_multiples(3, 10):")
print_multiples(3, 10)    # 3, 6, 9

print("print_powers_of_two(20):")
print_powers_of_two(20)   # 1, 2, 4, 8, 16
