9.12. 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.

System Message: ERROR/3 (/opt/web2py/applications/runestone/books/fopp/_sources/TransformingSequences/TheAccumulatorPatternwithStrings.rst, line 20)

Duplicate ID – see TransformingSequences/TheAccumulatorPatternwithLists, line 23

.. activecode:: ac8_10_1

   s = input("Enter some text")
   ac = ""
   for c in s:
       ac = ac + c + "-" + c + "-"

   print(ac)

Look carefully at line 4 in the above program (ac = ac + c + "-" + c + "-"). In words, it says that the new value of ac will be the old value of ac concatenated with the current character, a dash, then the current character and a dash again. 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).

Check your understanding

System Message: ERROR/3 (/opt/web2py/applications/runestone/books/fopp/_sources/TransformingSequences/TheAccumulatorPatternwithStrings.rst, line 60)

Duplicate ID – see TransformingSequences/TheAccumulatorPatternwithLists, line 92

.. activecode:: ac8_10_2
   :language: python
   :autograde: unittest
   :practice: T

   1. For each character in the string already saved in the variable ``str1``, add each character to a list called ``chars``.
   ~~~~
   str1 = "I love python"
   # HINT: what's the accumulator? That should go here.

   =====

   from unittest.gui import TestCaseGui

   class myTests(TestCaseGui):

      def testTwo(self):
         self.assertEqual(chars, ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'p', 'y', 't', 'h', 'o', 'n'], "Testing that chars is assigned to correct values.")
         self.assertIn('append', self.getEditorText(), "Testing your code (Don't worry about actual and expected values).")

   myTests().main()

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!

You have attempted of activities on this page