Q4: Sum Digits
Write a function that takes in a nonnegative integer and sums its digits. (Using floor division and modulo might be helpful here!)
1 | def sum_digits(n): |
Q6: Falling Factorial
Let’s write a function falling, which is a “falling” factorial that takes two arguments, n and k, and returns the product of k consecutive numbers, starting from n and working downwards.
1 | def falling(n, k): |
Q7: Double Eights
Write a function that takes in a number and determines if the digits contain two adjacent 8s.
1 | def double_eights(n): |
I Want to Play a Game
Now that you have learned about call expressions and control structures, you can code an algorithm! An algorithm is a set of steps to accomplish a task. You use algorithms every day – from adding numbers by hand to getting to your next lecture.
Let’s play a number guessing game with Python! Pick a number and Python will guess randomly until it guesses correctly.
All the code for this guessing game will be in lab01_extra.py. In your terminal, start an interactive session with Python:
1 | python3 -i lab01_extra.py |
The guess_random function will prompt you for a number, ask if its guess is correct (many times) and return the number of guesses Python had to make. To tell Python if its guess is correct, just enter y at the [y/n] prompt. If it’s wrong, enter n. Python isn’t very good at guessing yet, so if it’s taking too long, you can type Ctrl-C to make it stop.
1 | >>> guess_random() |
Randomly guessing works, but you can create an even better guessing strategy.
Q8: Guess Linear
One weakness in the guess_random strategy is that it can repeat (incorrect) guesses. Rather than guessing wildly, let’s guess numbers in increasing order.
Note: is_correct is a function that will ask the user if the guess is correct and return True if the user confirms that the guess matches the correct number. Feel free to reference the implementation of guess_random as you implement guess_linear.
1 | def guess_linear(): |
Q9: Guess Binary
Challenge question. The guess_linear function can take a long time if your number is large. However, a strategy called binary search can find the correct number faster. The idea is to start in the middle of the range and after each incorrect guess ask if the guess is_too_high or too low. Either way, you can eliminate half the remaining possible guesses.
Hint: Try using the is_too_high function to implement a faster strategy. is_too_high will return True if the guess is greater than the correct number.
1 | >>> result = is_too_high(5) |
Hint: You may want to update other variables besides guess.
1 | def guess_binary(): |