0

I downloaded Google's Python exercises and this is one of the questions:

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

My answer to this is given below:

def match_ends(words):
  a=[]
  for word in words:
    if len(word)>=2 and word[0]==word[-1]:
      a=a.append(word)
    return len(a)

However, for this list:

words=['aba', 'xyz', 'aa', 'x', 'bbb']

It just returns "1". I don't understand why append did not add all strings that match with if turn.

This is Google's solution:

def match_ends(words):
  count = 0
  for word in words:
    if len(word) >= 2 and word[0] == word[-1]:
      count = count + 1
  return count
Tagc
  • 8,736
  • 7
  • 61
  • 114
t.ztrk
  • 99
  • 1
  • 9

2 Answers2

5

There are two issues here:

  • an indentation issue:
def match_ends(words):
  a=[]
  for word in words:
    if len(word)>=2 and word[0]==word[-1]:
      a=a.append(word)
    return len(a)

The return statement is placed inside the for loop, meaning that after only one iteration, you will return an answer (either zero or one). So you can fix this like:

def match_ends(words):
  a=[]
  for word in words:
    if len(word)>=2 and word[0]==word[-1]:
      a=a.append(word)
  return len(a)
  • furthermore you assign the result of a.append(word) to a. .append however returns None (actually .append does not return anything, so Python let it automatically return None), so the next iteration, a is not a list anymore and the program would crash. So replace a = a.append(word) with a.append(word):
def match_ends(words):
  a=[]
  for word in words:
    if len(word)>=2 and word[0]==word[-1]:
      a.append(word)
  return len(a)

Now your program will work. Nevertheless it is useless to store all the matched words because you are only interested in counting them. You better use a counter and increment the counter if you found a match because this requires no additional memory. Google's answer is thus more efficient.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
1

Indent your return statement like this:

for word in words:
    if len(word)>=2 and word[0]==word[-1]:
        a.append(word)
return len(a)

When you placed it in the level of if it prints the length of the list a that now contains ['a'] as 1 (validated true for the first word that it found to have first and last letter to be the same) and exits since it is a return statement. The loop doesn't validate any other word in your list words.

Edited the answer as I didn't notice the assignment. append function doesn't need an assignment. Thank you @Willem

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555