CS 240: Data Structures and Algorithms
James Madison University, Fall 2014

In Class Activity #2: Lists, Strings and Control

Objectives

The goal of today's activity is to get comfortable working with basic features of the Python programming language including Python lists, strings and control flow constructs.

Resources

Here are links to the pertinent sections of the Python documentation:

You may also be interested in the complete list of string methods.

Exercises

  1. Removing Letters
    • Create a new .py file to contain today's work. Include your name and today's date in a comment at the top of the file.
    • Write a function with the following signature:
              remove_letter(sentence, letter)
              
      This function should take a string and letter (a single-character string) as arguments, and return a copy of that string with every instance of the indicated letter removed. For example, remove_letter("Hello there!", "e"), should return the string "Hllo thr!".

      Hints:
      • Remember that a string is sequence of individual characters. Python allows you to iterate over the characters of a string using the same syntax as a list iteration:
                    for ch in "Hello!":
                        print(ch)
                    
      • Remember that the "+" symbol is used for string concatenation. I can create the string "Hi" as follows:
        		    greeting = ""
        		    greeting = greeting + "H"
        		    greeting = greeting + "i"
        		  
        Or, equivalently:
        		    greeting = ""
        		    greeting += "H"
        		    greeting += "i"
        		  
    • Add a main() function to your program and use it to test remove_letter. Recall that the following idiom is commonly used in Python and is required in this class by the style guide:
                      def main():
                          # your code goes here
                      
                      if __name__ == "__main__":
                          main()
      
              
  2. Find and Replace
    • Write a function with the following signature:
              replace_word(sentence, target, replacement)
              
      This function will take three strings as arguments. The first will contain a sentence, the second will contain a word to replace, and the third will contain the replacement word. The return value should be a copy of sentence with every instance of original replaced with an instance of new. For example,
      		replace_word("I am happy to meet you!", "happy", "angry")
      	      
      should return the string "I am angry to meet you! ". Don't worry about handling punctuation correctly. Punctuation marks may be considered part of the word that they follow. (Note that Python strings have a built-in replace method that can accomplish this in a single line of code. Don't use it! Solve the problem by iterating over the words in the string.)

      Hints:
      • Python strings have a split method that splits the string into a list of words. For example, after the following code segment:
         
        		    greeting = "hello there"
        		    words = greeting.split()
        		  
        words will contain the list ['hello', 'there'].
    • Test your new function from main. I suggest testing this function in conjunction with remove_letter as follows:
              angry = replace_word("I am happy to meet you!", "happy", "angry")
              no_y = remove_letter(angry, "y")
              print(no_y)
              
      The result should be "I am angr to meet ou!".
  3. Reversing a Sentence
    • Write a function with the following signature:
              reverse_sentence(sentence)
              
      This function should take a string as an argument, and return a new string in which the order of the individual words has been reversed. Don't worry about separating and preserving punctuation; it's ok to treat it as if it was part of the word preceding it.

      Hints:
      • There are at least two reasonable ways to solve this problem: 1) You could iterate forward through the existing words, and append each subsequent word to the beginning of a new string, or 2) You could iterate backward through the existing words and append each subsequent word to the end of a new string. Iterating backward can be accomplished either by passing a negative third argument to the range function or by using negative list indexing. (where -1 refers to the last element in the list, -2 to the second-to-last, etc.).
    • Test your new function from the main.
  4. String Formatting (optional)
    • Write a function with the following signature:
              format_str(description, values)
              
      This function should return a reformatted version of description, where special identifier words like "$3" have been replaced by the specified element from values. The special identifiers should always be a single word (no spaces) composed of a single dollar sign ("$") followed by the zero-based index of the desired value.

      Your function should work regardless of whether the values are strings, integers, or floating-point numbers. Your function should also check to make sure the given index is within the bounds of the given list. If it is not, your function should insert the text "ERROR".

      Here are some examples:
              format_str("Hello $0", ["Mike"])
                  # result: "Hello Mike"
      
              format_str("The sum of $0 and $1 is $2", [3,5,8])
                  # result: "The sum of 3 and 5 is 8"
      
              format_str("The name is $1 -- $0 $1", ["James", "Bond"])
                  # result: "The name is Bond -- James Bond"
      
              format_str("Names: $0 $1 $2 $3", ["Mike", "Nathan"])
                  # result: "Names: Mike Nathan ERROR ERROR"
              
      Hints:
      • To extract the index number from a special identifier, you may wish to use a technique called slicing. You can find information about it in the Python string documentation.
    • Test your new function from main().

Finishing Up

There is nothing to hand in for this assignment. Make sure that you save a copy of your code. If you worked with a partner, make sure both of you get a copy.