Homework Assignment
CS 121 (CS1)
- Homework 12 Due Monday, March 10, 2014
-
-
Strings [hc]
-
Postponed
-
Text questions: Strings, Exercises 10
-
Hints:
-
Here is a spec for the desired function.
countMatches
- 2 arguments: A non-empty string and any other string
- Return: A non-negative integer, the number of times arg1 appears as a substring of arg2.
countMatches("a", "Hawaii") --> 2 countMatches("h", "Hawaii") --> 0 countMatches("wa", "Hawaii") --> 1 countMatches("h", "") --> 0
-
Here are two approaches to solving this problem.
- Approach #1
-
Use an index as a loop control variable in a
for
loop. -
For each index position in the string arg2, use
==
to compare arg1 to a slice of arg2 that begins at that index and continues for the length of arg1. (Add that length to that index to find the end of the slice.) -
Use an accumulator to count the number of matches found.
-
- Approach #2
-
Use a
while
loop whose guard uses the stringfind()
method.str.find
- 2 arguments: A string and an integer indicating a position in an string object (e.g., an index). If arg2 is missing, that second argument is treated as 0.
- Return: An integer, the lowest integer where arg1 appears in a string object, starting the search at position arg2. Return -1 if arg1 does not appear in that string object.
"Mississippi".find("is") --> 1 "Mississippi".find("is", 2) --> 4 "Mississippi".find("it") --> -1 "Mississippi".find("is", 5) --> -1
Notes:-
In this spec, "a string object" refers to the string whose method is being called, e.g.,
"Mississippi"
. -
The type
str
is a built-in type in Python3, so noimport
statement is necessary in order to use this method.
-
For that
while
loop, initialize a variable position at 0, and also use an accumulator to count the matches found so far. If thefind()
method detects match (in the guard of thatwhile
loop), add 1 to the count and change the position to just after the location where that match was found.
-
- Approach #1
-
-
-
-
Images [hc]
Postponed
-
Recursion [hc]
Recursion questions, 10f, 11c
-
Computing with trees [hc]
Recursion questions, 12 c
-
Review questions [hc]
-
Reading
-
--
(This part is a reminder for the reading assignment HW11F.) Read online text: Lists.
submit at least one reading question by 9am before Monday.Note: Please also read Files for Monday. You may submit a question on Files if desired; however, you are only required to submit a question for Lists
-
-