Problem decomposition
Real computational tasks are complicated. To accomplish them you need to think
before you code.
Problem decomposition steps
- Understand the problem
1 Restate the problem in your own words.
- Know what the desired inputs and outputs are.
- Ask questions for clarification (in class these questions might be to
your instructor, but most of the time they will be asking either yourself
or your collaborators).
- Break the problem down into a few large pieces. Write these down, either on
paper or as comments in a file.
- Break complicated pieces down into smaller pieces. Keep doing this until all
of the pieces are small.
- Code one small piece at a time.
- Think about how to implement it.
- Write the code/query.
- Test it… on it’s own.
- Fix any problems.
- One way to do this is to identify functions.
Example
Calculate the volume of a bunch of shrubs.
Data
length,width,height
1, 2, 3
2, 4, 3
- Calculate the volume of a shrub
a. Function
- Run this calculation on all shrubs
a. Loop
Write either first.
Make a simpler version first
If you aren’t sure how to do something, make a simpler version that you do know
how to do first.
- Experiment
- Write a simpler version
- Make sure it works
- Make sure you understand it
- Modify it to make it more complicated
- Repeat until finished
Converting code into functions
If making a function work is confusing, start without a function and then
convert it into a function.
- Write a specific example of what the function should do
- Create variables to hold the specific values you used
- Replace the specific values in your example with the variables
- Use the names of those variables in the function definition
- Indent
- Remove the initial definition of the variables
- Return you answer
- Call the function