Pages

Tuesday, October 30, 2012

PY-04: Solving Problems, Part 2

In the last post, I covered how decrementing functions can be useful for finding the solutions to simple problems, notably for finding a cubed root of a value, "x". However, it is important to note that while decrementing functions are sometimes the best call, they are not always so. Our next lesson covers another method, by the name of exhaustive enumeration.


Before we begin, please note that open and close brackets, i.e. "[" and "]" respectively, will contain raw code.

Exhaustive Enumeration

Summary

Exhaustive enumeration is a function for solving problems by which the computer exhausts possible options in a systematic way, so that it can find the correct one. This is what is known in the world of programming as a "brute force" tactic for solving problems, because of its straight-forward methods.

As computers are so adept at computing instructions swiftly, once outlandish ways to solve problems are now useful realities. An example of exhaustive enumeration in real life (albeit a watered-down version) would be finding which answers on a multiple-choice test question are not correct, and by process of elimination (exhaustion), we can come to the correct answer more easily.

Coding

Range is a built-in function of Python that generates a sequence (usually, it is a sequence of integers). It is also a type of tuple (which we will cover in coming lessons).

[ range(x,y) ] will generate a sequence starting at the value "x", and will continue until the value "y-1". While the value "x" is mandatory, "y" is optional. Starting at "x" probably makes sense to you, but the ending value of "y-1" may be a bit more confusing. This is because Python starts counting at 0 instead of 1, which means the position of "x" in the range is not 1st, but actually 0th. The value "x+1" follows in the 1st spot, and so on

If this is confusing, please do some more reading on this, as I myself do not know the in-depth reasoning behind it. E.W. Dijkstra wrote a paper about the complicated but important concept of "0-based indexing" here. You don't necessarily need to understand why it works in this way to program properly, but it could save you a ton of time in the future. Your choice!

Example

>>> range(5)
[0, 1, 2, 3, 4]
>>> range(2,5)
[2, 3, 4]

Also, break is a great statement to remember. It prematurely exits the loop, even in the middle of a "range" function. This can be useful for a variety of things, which I am sure you will come to soon discover. One such use would obviously be to end a loop at a specific point, instead of running it to completion; another might be for troubleshooting. To use the break statement, simply add [break].


Coming next, in PY-05, we will discuss our final (and perhaps most complicated) method of problem solving: approximation!

No comments:

Post a Comment