9.13 The Accumulator Pattern with Strings
From Foundations of Python ProgrammingGNU FDL 1.3Original pagePython1 class period2 exercises2 graded tests
9.13 The Accumulator Pattern with Strings
We can also accumulate strings rather than accumulating numbers, as you've seen before. The following program isn't particularly useful for data processing, but we will see more useful things later that accumulate strings.
s = input("Enter some text")
ac = ""
for c in s:
ac = ac + c + "-"
print(ac)
Look carefully at line 4 in the above program (ac = ac + c + "-"). In words, it says that the
new value of ac will be the old value of ac concatenated with the current character and a dash.
We are building the result string character by character.
Take a close look also at the initialization of ac. We start with an empty string and then begin adding
new characters to the end. Also note that I have given it a different name this time, ac instead of
accum. There's nothing magical about these names. You could use any valid variable and it would work the
same (try substituting x for ac everywhere in the above code).
We can use the accumulator pattern to reverse a string, as in the following code.
s = "Murphy"
ac = ""
for c in s:
ac = c + ac
print(ac)
The key thing here is that we have ac = c + ac. The iterator variable comes first, before the accumulator.
We are pre-pending the new value onto the beginning of the value that has been accumulated so far, and that leads to
reversing the whole string. Try it in codelens if you're having trouble envisioning why this works.
Note
A little humorous aside... You've probably heard of Murphy's Law, that everything that can go wrong will go wrong.
In a paper co-authored by one of this book's authors, we described eBay's reputation system as an example of Yhprum's Law (Yhprum is Murphy spelled backward, with a little change in capitalization): "Systems that shouldn’t work sometimes do, or at least work fairly well."
Check your understanding
Check your understanding: a multiple-choice question in the book.
Exercise 1
- Accumulate all the characters from the string in the variable
str1into a list of characters calledchars.
Open the
01folder and editmain.py. Run Tests checks it.
Exercise 2
Assign an empty string to the variable output. Using the range function, write code to make it so that the variable output has 35 a s inside it (like "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"). Hint: use the accumulation pattern!
Open the
02folder and editmain.py. Run Tests checks it.
For teachers
9.13 The Accumulator Pattern with Strings
Students read Foundations of Python Programming's “The Accumulator Pattern with Strings” in CS Room and work through its 2 Python coding exercises (2 graded).
- Time: 1 class period
- Tests: 2 in 2 graded exercises, set up for you when you import the lesson
Exercises
| Folder | Grading | Tests |
|---|---|---|
01 | Autograded | 1 |
02 | Autograded | 1 |