Skip to main content

Section 1.9 HW5

Exercises Exercises

1. First Three Characters in a String.

The function first_three takes one string parameter, word, and returnsaΒ slice of length three from the front of word.Β  However, if word has length less than three, then the None object is returned instead.
Hint: Use an if-else decision and the slicing operator [ : ] to solve this problem.
For example:
Test Result
first_three("happy")
hap
first_three("dog")
dog
first_three("")
None

2. .

Slice the End of a String
The function slice_end takes a string parameter, word, and a positive integer n; the function returnsaΒ slice of length n from the end of word.Β  However, if word has length less than n, then the None objectΒ is returned instead.
Hint: Notice that returning the empty string when n is zeromight be a special case.
You can use an if-elif-else decision structure and the slicing operator [ : ] to solve this problem.
For example:
Test Result
slice_end("pineapple", 5)
apple
slice_end("too short", 20)
None
slice_end("llama", 0)
slice_end("Saturn", 6)
Saturn

3. Slice the Middle of a String.

The function slice_middle takes a string parameter, word.
  • If the length of word is less than 3, the function returns the empty string.
  • Otherwise, the function returns a substring made of all but the first and last characters in word.
For example:
Test Result
slice_middle("onion")
nio
slice_middle("?")
slice_middle("slicing")
licin

4. Add Character Counts.

The function add_char_counts takes three parameters: a string s and two strings of length 1, char1 and char2, and returns the total number of times either char1 or char2 appears in s.
For example, the word "scallions" has 2 s’s and 1 n, so add_char_counts("scallions", "s", "n") returns 3.
Hint: Use a string method to help solve this problem (count).Β  You do not need an accumulator.
For example:
Test Result
add_char_counts('Indiana', 'a', 'b')
add_char_counts('BAHAMAS', 'A', 'B')
add_char_counts('Mississippi', 'i', 'M')
add_char_counts("spam spam spam spam", "s", "p")

5. Count Words of a Given Length.

The function countWordsOfLength takes a list of words L and an integer n, and returns the total number of words of length n that appear in the list. For example, countWordsOfLength(["yes", "no", "maybe", "NNOOO"], 5) would return 2 because the given list has two words of length 5.
Hint: Use the accumulator pattern to solve this problem. Inside the for loop, use an ifstatement to only update the accumulator when the current word has length n.
Hint: Instead of using a for loop with a range, you can iterate directly overΒ  the elements of L.
For example:
Test Result
L = ['a', 'b', 'c', 'de', 'fgh', 'i', 'jkl']
countWordsOfLength(L, 1)
L = ['a', 'b', 'c', 'de', 'fgh', 'i', 'jkl']
countWordsOfLength(L, 5)
L = ['bacon', 'onion', 'pepper', 'garlic', 'paprika', 'chipotle chili powder', 'salt', 'black pepper', 'vinegar', 'bbq sauce', 'ketchup', 'mustard', 'brown sugar', 'beans']
countWordsOfLength(L, 5)

6. Make Abbreviation.

The function make_abbreviation takes one parameter, wordlist, a list of words, and produces an acronym out of the words in the list, with a period after each initial character.Β  The function returns the resulting acronym string.
For example, the input ["International", "Business", "Machines"] would cause the function to return "I.B.M."
Write a function definition for make_abbreviation.
Hint: Use the accumulate-a-string pattern.
- Initialize the accumulator variable to "", the empty string.
- Iterate w over the items wordlist
- Inside the for loop, update the accumulator variable by concatenating it with the first character in the current word as well as a period.
For example:
Test Result
wordlist = ["Post", "Meridiem"]
make_abbreviation(wordlist)
P.M.
wordlist = ["Joint", "Photographic", "Experts", "Group"]
make_abbreviation(wordlist)
J.P.E.G.

7. Count Contains ’X’ or ’x’.

The function count_contains_x takes a list of strings (wordList) and returnsthe count ofΒ how many strings in the list contain at least one upper- or lower-case ’x’.
Hint: Use the accumulator pattern to accumulate the count.
For example:
Test Result
wordList = ["xerox", "OXEN", "whiffleball", "XOXOX"]
count_contains_x(wordList)
fish = ["angel", "gold", "cat", "puffer", "damsel"]
count_contains_x(fish)
wordList = ["X", "x"]
count_contains_x(wordList)
list_of_one_x = ["x"]
count_contains_x(list_of_one_x)

8. Remove Vowels.

The function remove_vowels takes one parameter, s, a string of any length. The function then returns a new string that contains all the letters in s except for the vowels: ’a’, ’e’, ’i’, ’o’, ’u’.
You may assume the string contains no upper-case letters.
Hint: Accumulate the new string.
  • Use a for loop to iterate over the characters in s
  • Inside the loop, update the accumulator if the current character is not a lowercase vowel ( if ch not in 'aeiou' )
For example:
Test Result
remove_vowels("giraffe")
grff
remove_vowels("love bug")
lv bg
remove_vowels("racecar")
rccr
remove_vowels("uoiea")

9. Decode from ASCII.

The function decodeFromAscii takes a list L of integers in the range 32 through 126. Each item in L is an ASCII code representing a single printable character. The function accumulates the string of characters represented by the list of ASCII codes and returns that string.
For example, decodeFromAscii([78, 105, 99, 101, 33]) returns "Nice!" because N is chr(78), i is chr(105), c is chr(99), etc.
Note: ASCII was created in the 1960’s so programmers could have a standard encoding for common keyboard characters as numbers. It was later expanded to create Unicode so that characters from languagesΒ  other than English, mathematical symbols, and many other symbols could also be represented by numerical codes.
For example:
Test Result
decodeFromAscii([36, 49, 44, 48, 48, 48])
$1,000
decodeFromAscii([115, 110, 111, 119])
snow

10. Concatenate Alternating Characters.

The function concatAltChars takes a string parameter s and a boolean parameter even; the function concatenates together either the even-position characters of s or the odd-position characters of s, depending on whether even is True, or False, respectively. The accumulated string is returned.
For example, the even-indexed characters of "HANOVER" are at indexes 0, 2, 4, and 6:Β  H N V R. So, concatAltChars("HANOVER", True)returns the string result "HNVR".
But concatAltChars("HANOVER", False) returns the string result "AOE".
For example:
Test Result
concatAltChars('goldfinches', True)
glfnhs
concatAltChars("A", True)
concatAltChars("A", False)

11. String Has Repeated Character?

Write the code to define a function has_repeat(mystr), which takes a string parameter and returns a boolean result.
- If mystr has a character that is repeated (count is more than 1 for that character), return True
- Otherwise, return False
Hint: You can solve this problem by iterating over the characters in mystr and comparing each character’s count with 1.
For example:
Test Result
has_repeat("Happy")
True
has_repeat("sad")
False
has_repeat("salmons")
True
has_repeat("Trouts")
False

12. String Has Adjacent Repeated Characters?

Write the code to define the function has_adjacent_repeats(mystr), which takes a string parameter and returns a boolean result.
- If mystr has at least one instance of adjacent characters being equal, return True
- Otherwise, return False
Hint: You can iterate over the positive indices i for characters in mystr: 1, 2, 3, ...., len(mystr)-1 with a for loop. For each i, if the character at index i matches the character at index i - 1, return True. Otherwise, if no doubled character is found in the entire string, return False.
For example:
Test Result
has_adjacent_repeats("NOODLES")
True
has_adjacent_repeats("Bananas")
False
has_adjacent_repeats("Hanoverr")
True

13. String is Numberlike?

mystr is "numberlike" if:
- mystr is not the empty string
- the first character in mystr is a digit
- the count of ’.’ in mystr is zero or one (can’t have more than one decimal point in a number)
- every character in mystr is a digit (’0’, ’1’, ’2’, ..., ’9’) or a decimal point (’.’)
Write the code to define the function is_numberlike(mystr), which takes a string parameter and returns a boolean result.
If mystr is numberlike, the function returns True; otherwise, the function returns False.
Hint: Check the first three requirements with decision statements, then use a forloop to iterate over mystr and check the every character is a digit or a dot
For example:
Test Result
if not (is_numberlike("13.5") is True):
    print("error")
if not (is_numberlike("-5532") is False):
    print("error")
if not (is_numberlike("175") is True):
    print("error")

14. Find Max Char.

The function find_max_char takes one string parameter, mystr. The function returns the character in mystr with the maximum ordinal value (the character that comes last in the ASCII alphabet, relative to the other characters in mystr).Β However, if mystr is the empty string, the function returns the Python object None.
Notice that we don’t need the ord() function to compare ordinal values; we can use comparison operators. For example, "Z" > "C" is true because Z comes after C in the ASCII alphabet.
We need to "accumulate" the correct answer (max_char) and then return it:
  • First, if mystr is empty, return None
  • Then initialize max_char (accumulator variable) to the first character in mystr
  • Use a for loop to iterate ch over the characters in mystr
  • Each time a new maximum character is found (if ch > max_char), max_char is updated to "remember" that the new maximum is ch
  • Finally, return max_char
For example:
Test Result
find_max_char("naproxen")
find_max_char("Gorilla Glue")
find_max_char("")
None
You have attempted of activities on this page.