[Tutor] Stuck on Challenge in Google Python Class

spir denis.spir at gmail.com
Wed Jan 22 10:38:54 CET 2014


On 01/22/2014 05:24 AM, 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.
> # Note: python does not have a ++ operator, but += works.'
>
> Try #1:
>
> 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

1. What is asked for is just the number of strings matching a given criterion, 
right? So you don't need to collect them into a list, then get the list's count 
of items: you could just count them as you go (as you traverse them in the 'for' 
loop).

2. You criterion is wrong. Please read again the problem and compare to your 
translation into programming code:
	(len(string) >= 2) or (string[0] == string[-1])

[If you cannot find a right solution according to 1. & 2., we'll help you further.]

> def match_ends(words):
>
> # Calls the above functions with interesting inputs.
> def main():
>    print 'match_ends'
>    test(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']), 3)
>    test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 2)
>    test(match_ends(['aaa', 'be', 'abc', 'hello']), 1)
>
>
> Tries 2 and on: I wanted to get just the part working to check to see if
> the first and last character are the same. I tried setting up a for loop
> within a for loop. The first loop cycles through each word in the list,
> then the second for loop cycles through each letter to compare if the first
> character is equal to the last or not. I cannot get it to compare the first
> and last letter properly.

1. The first half of the criterion is necessary for the second half to make 
sense, isn't it? (think hard ;-)
2. There is no simple way to compare first & last chars by iterating through all 
chars (you need to memorise the first char, then wait until you reach the last 
one, then only compare), and it is big overkill. Why do you want to do that at 
all? (you'd have to do that if python lists were linked lists, but they are 
flexible-size *arrays*: you can access any item by index)

Finally, an interesting challenge: generalise this into a function that counts 
the number of items in a collection (list, set...) matching a given criterion:

	def n_matches (coll, crit):
	    # ....
	    return n

[This could be a python builtin func or method, if it were commonly needed.]

Denis


More information about the Tutor mailing list