Practice with Strings and Loops (from 15-110 Spring
2011 Homework 3)
Note: these problems were originally written for 15-110 Spring
2011 Homework 3. Of course, you may ignore references to hw2 here (they do
not correspond to this semester's hw), and you may also ignore any other
out-of-context references.
These are optional practice problems to help you prepare for
hw3. Solutions are provided, along with
short video tutorials.
Here are the files you'll need:
- hw3-practice.py: starter code (download this and replace the stubs with your answers)
- hw3-practice-solutions.py: sample solutions (note that there are many other perfectly valid solutions!)
-
hw3-practice-videos.html: short video tutorials explaining the sample solutions, and a brief overview of how to get started on hw3.
Note: This week, you may use "if" statements
(conditionals), and "for" or "while" statements (loops), but you may not use recursion, or
collections (lists, dictionaries, etc). Since we have not
covered these yet, this should not be a concern for most of
you.
- maxChar
- evenChars
- reverseString
- vowelCount
- maxChar
Without using max(s), return the character with the maximum Unicode
value in the string s. If s has no characters, return None. Here are some test cases for you:
assert(maxChar("abcdefabcd") == "f")
assert(maxChar("abcdefabfcd") == "f")
assert(maxChar("ABDFDSFA") == "S")
assert(maxChar("ABDFqDSFA") == "q")
assert(maxChar("ABD{FqDSFA98754") == "{")
assert(maxChar("") == None)
- evenChars
Write a function that takes a string s and returns the string formed by the characters at even indexes of s. Here are some test cases for you:
assert(evenChars("abcdefg") == "aceg")
assert(evenChars("") == "")
assert(evenChars("a") == "a")
assert(evenChars("ab") == "a")
- reverseString
Write
the function reverseString that takes a string and returns the reverse
of that string (so "abc" becomes "cba"). Do this from first
principles, with loops and conditionals, and not using a built-in
reverse function or slicing like s[::-1] or converting the string to a
list or anything else of that nature. Here are some test cases for you:
assert(reverseString("abcde") == "edcba")
assert(reverseString("abcdef GH") == "HG fedcba")
assert(reverseString("a") == "a")
assert(reverseString("") == "")
- vowelCount
Write the function vowelCount that takes a string and returns the number of vowels in it (case-insensitively). Here are some test cases for you:
assert(vowelCount("abcdefg") == 2)
assert(vowelCount("ABCDEFG") == 2)
assert(vowelCount("") == 0)
assert(vowelCount("This is a test. 12345.") == 4)
carpe diem -
carpe diem - carpe diem - carpe diem
- carpe diem - carpe diem -
carpe diem - carpe diem - carpe
diem