In this chapter I learned about using the search tool with binary logic. Referred as to a “binary search”. This allows for shorter and more efficient ways to gather information for example having a game where a the computer has to figure out the number.

`import`

`random`

`secret_number `

`=`

`random.randrange(`

`1`

`, `

`129`

`)`

`guess `

`=`

`0`

`while`

`guess !`

`=`

`secret_number:`

` `

`guess `

`=`

`(`

`int`

`)(`

`input`

`(`

`"Guess a number 1 to 128: "`

`))`

` `

`if`

`guess < secret_number:`

` `

`print`

`(`

`"Too low."`

`)`

` `

`elif`

`guess > secret_number:`

` `

`print`

`(`

`"Too high."`

`)`

` `

`else`

`:`

` `

`print`

`(`

`"Correct!"`

`)`

Using binary search we can reduce the amount of guesses the computer will take. For linear it would guess 1 to 129 but with binary we give the computer an idea of how to do it more efficiently. In this case we will use half of the range of the secret number.

`Binary search`

`key `

`=`

`"Secret Number"`

`lower_bound `

`=`

`0`

`upper_bound `

`=`

128`found `

`=`

`False`

`while`

`lower_bound <`

`=`

`upper_bound `

`and`

`not`

`found:`

` `

` `

`middle_pos `

`=`

`(lower_bound `

`+`

`upper_bound) `

`/`

`/`

`2`

` `

` `

`if`

secret_number`[middle_pos] < key:`

` `

`lower_bound `

`=`

`middle_pos `

`+`

`1`

` `

`elif`

secret_number`[middle_pos] > key:`

` `

`upper_bound `

`=`

`middle_pos `

`-`

`1`

` `

`else`

`:`

` `

`found `

`=`

`True`

`if`

`found:`

` `

`print`

`( `

`"The number is "`

`, middle_pos)`

`else`

`:`

` `

Advertisements