Wednesday, December 10, 2014

Activity 1.3.8 - While Loops

Number Guesser Code:

I always have to shrink these pictures down a lot so they don't mess with the blog's appearance

Conclusion Questions:

1.) If you change between 1 and 20 from the previous program to between 1 and 6000, how many guesses will you need to guarantee that you have the right answer? Explain.

The most efficient way to guess would be to guess the number directly in the middle of the low and high to see if that guess is too high/too low. That allows you to remove half of the numbers from what you have to guess next. For example, between 1 and 20, you would guess 10. If 10 is too high, then your next guesses would be limited to 1-9, because you're told that 10+ is too high. Then you would keep checking the new number that is halfway between the new high and low, and continue doing that until you're left with two numbers to guess from. Cutting the total number of possible answers in half each time, this method creates a logarithmic pattern - e.g. 256, 128, 64, 32, 16, 8, 4, 2, 1. So, the number of guesses you'd need has to be the lowest power of two that's greater than the number of choices. 2^13 = 8192, which is higher than 6000 and the lowest power of two that creates such a number. So, with this method, it'd only take 13 guesses to get the number!

2.) Describe the difference between a while loop and a for loop.

A for loop is often used for lists and tuples. It runs a set of instructions for each item within an array of values. A while loop is used with conditional expressions that could run for an indefinite amount of time, unlike for loops, which simply run through a list.

No comments:

Post a Comment