Friday, October 26, 2012

PY-03: Solving Problems, Part 1

Programs are very useful for the purpose of solving problems. Many programmers know this potential of programs, and use it to their advantage. However, all is not so straight-forward in the world of programming and problem-solving; there are as many ways to go about finding a solution as there are stars in the sky (perhaps more!).

All in all, the method by which you code a program for finding the solution to a problem is up to the programmer -- you. That is why it is important to learn some of the basic ways by which one can arrive at a solution. Only after you understand these ways, can you move on to more complicated problem-solving.

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

Decrementing Function

The first method is the decrementing function. A decrementing function starts with a non-negative value, which is decreased each time the program repeats the function's loop. The function will loop so long as the starting value is non-negative, but once it is equal to or less than 0, it will terminate.

ExampleFind the cubed root of a value, "x", using a decrementing function.

[ ans * ans * ans = x ], where "ans" is the computer's guess (which will eventually be the answer), is one way to go about finding the cube root of a value, "x". 

However, a more efficient method would be the decrementing function [ abs(x) - ans^3 ], where "abs(x)" is the absolute value of a value, "x", and "ans^3" is the computer's guess, cubed.

Remember, a decrementing function terminates when the starting value is equal to or less than 0; the only way this can happen for our example function is if the computer's guess is the cubed root of the value "x". Therefore, the program will terminate when the computer has guessed the correct answer!

The next post, PY-04, will continue the current series of Solving Problems in Python. Specifically, Part 2 will cover an even more convenient method of finding a solution -- exhaustive enumeration!

No comments:

Post a Comment