[Tutor] Stuck on Challenge in Google Python Class
Steven D'Aprano
steve at pearwood.info
Wed Jan 22 12:07:47 CET 2014
On Tue, Jan 21, 2014 at 08:24:54PM -0800, Adam Hurwitz wrote:
> Hi,
>
> This is a coding challenge in the Google Developers Python
> Course<https://developers.google.com/edu/python/exercises/basic>.
> I have been working on this challenge for hours without being able to solve.
>
> A. match_ends
> # Given a list of strings, return the count of the number of
> # strings where the string length is 2 or more and the first
> # and last chars of the string are the same.
How would you solve it as a human being?
Start with the count of matching strings as zero.
Look at each string in turn, one at a time.
If that string has length greater than two, AND the ends match, increase
the count by one.
Start with that, then turn it into Python code as below:
> def match_ends(words):
> numberStrings = [ ]
> answer = ' '
> for string in words:
> if len(string) >=2 or string[0] == string[-1]:
> numberStrings.append(string)
> else:
> return ' '
> answer = len(numberStrings)
> print answer
No need to record each string itself. You only need to count them.
count = 0 # start with count of zero
count += 1 # add one
Also, take note that the condition described is that the length of the
string is two or greater, AND that the ends match. You have that the
length of the string is two or greater, OR that the ends match.
--
Steven
More information about the Tutor
mailing list