Programming with Python

Stefan Güttel, guettel.com

Exercises: Strings and generators

Problem 1. Write a function copy_rev(s) that takes a string s and returns a new string that consists of an original string s followed by its reverse copy.

For example, copy_rev("aBcd") should return "aBcddcBa".

Problem 2. Write functions

  • copy_to_len_whole(s, l) that returns the maximum length string made of copies of s (only the whole s, no slicing) with the length at most l,
  • copy_to_len_sliced(s, l) that returns the maximum length string made of copies of s with the length exactly l; if the length of s doesn't match, it ends with the beginning slice of s.

For example,

  • copy_to_len_whole("12345", 17) should return "123451234512345" (length 15);
  • copy_to_len_sliced("12345", 17) should return "12345123451234512" (length 17).

You may assume that s is not an empty string and that l >= 0.

Problem 3. Write functions

  • fade_copies_left(s) that returns the string made by concatenating s with its left slices of decreasing sizes, i.e., with the s without the last character, then with s without the last two characters, etc;
  • fade_copies_right(s) that returns the string made by concatenating s with its right slices of decreasing sizes, i.e., with the s without the first character, then with s without the first two characters, etc.

For example,

  • fade_copies_left("abcde") should return "abcdeabcdabcaba";
  • fade_copies_right("abcde") should return "abcdebcdecdedee".

Problem 4. We define words as sequences of non-space characters separated by a single space.

Write a function last_word(s) that returns the last word in s, i.e., the substring beginning after the last occurence of the space character " " in s all the way to the end. If the string s ends with a space, the function returns an empty string "". If the string contains no spaces, the whole string is its last word.

Further, write a main() function that loads an integer n and then n strings which it prints sorted by the last word.

Problem 5. We define words as sequences of non-space characters separated by a sequence of consecutive spaces (one or more of them).

Write a function second_word(s) that returns the second word in s. Words are mutually separated by one or more spaces. You may assume that s will not start with a space.

For example, in the string "This is a sentence." the second word is "is" even though there are 5 spaces before it.