Presentation is loading. Please wait.

Presentation is loading. Please wait.

The Accumulator Pattern Motivating Example: Suppose that you want to add up (“accumulate”) 1 2 plus 2 2 plus 3 2 plus … plus 1000 2 You could use: total.

Similar presentations


Presentation on theme: "The Accumulator Pattern Motivating Example: Suppose that you want to add up (“accumulate”) 1 2 plus 2 2 plus 3 2 plus … plus 1000 2 You could use: total."— Presentation transcript:

1 The Accumulator Pattern Motivating Example: Suppose that you want to add up (“accumulate”) 1 2 plus 2 2 plus 3 2 plus … plus 1000 2 You could use: total = (1 ** 2) + (2 ** 2) + (3 ** 2) + (4 ** 2) + [etc to 1000] But that would be painful (and impractical) So instead use a loop, like this: Let’s act that out (next slide): X ** Y means X raised to the Yth power total starts at zero Loop 1000 times: total becomes what it was + next item to add to total

2 The Accumulator Pattern, acted out Using a loop to compute 1 2 plus 2 2 plus 3 2 plus … plus 1000 2 total starts at 0 total becomes 1 total becomes 5 total becomes 14 total becomes 30 total becomes 55 total becomes 91... total starts at zero Loop 1000 times: total becomes what it was + next item to add to total We add in 1 2 (which is 1), so... We add in 2 2 (which is 4), so... We add in 3 2 (which is 9), so... We add in 4 2 (which is 16), so... We add in 5 2 (which is 25), so... We add in 6 2 (which is 36), so... and so forth

3 The Accumulator Pattern, in Python This summing version of the Accumulator Pattern, applied to this problem of summing squares, is written in Python like this: total = 0 for k in range(1000): total = total + (k + 1) ** 2 total starts at zero Loop 1000 times: total becomes what it was + next item to add to total Inside the loop, put: total = total +... Lousy mathematics, but great computer science! Read = as “becomes”. Use a variable, which we chose to call total, and initialize that variable to 0 before the loop Use a range expression in a for loop After the loop ends, the variable total has as its value the accumulated sum!

4 The Summing version of the Accumulator Pattern total = 0 for k in range(BLAH): total = total + STUFF The Accumulator Pattern for summing Inside the loop, put: total = total +... Lousy mathematics, but great computer science! Read = as “becomes”. Use a variable, which we chose to call total, and initialize that variable to 0 before the loop Use a range expression in a for loop After the loop ends, the variable total has as its value the accumulated sum!


Download ppt "The Accumulator Pattern Motivating Example: Suppose that you want to add up (“accumulate”) 1 2 plus 2 2 plus 3 2 plus … plus 1000 2 You could use: total."

Similar presentations


Ads by Google