-4

the task here is :

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.

def match_ends(words):
    for i in words:
        if (len(i) >= 2) & (i[0] == i[-1]):
            return [i]


print(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']))

and the output is :

['aba']

3 Answers3

1

the problem is that returns the first and it doesn't keep going

the return keyword stops the function, so you have to store it in an array-like to return it

here is the code optimized:

def match_ends(*words):
    result = []
    for i in list(words):
        if len(i) >= 2 and i[0] == i[-1]:
            result.append([i])
    return result


print(match_ends('aba', 'xyz', 'aa', 'x', 'bbb'))
XxJames07-
  • 1,833
  • 1
  • 4
  • 17
0
if (len(i) >= 2) & (i[0] == i[-1]):
     return [i]

You return when your if condition is true, and this will stop your function.

You should then save your data in a variable if you want to get all the occurence of it as res.append(i) (save i in the list res)

Then return it outside when you have iterate through all your list.

def match_ends(words):
    for i in words:
        if (len(i) >= 2) & (i[0] == i[-1]):
            res.append(i)
    return res
SneaKoa
  • 50
  • 4
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – taylor.2317 Dec 29 '21 at 17:23
0

This is happening because your first item matches your if conditions and as you are using return, your code exits with the result as the first item. I am not sure what you want to do with this function.

Saurav Panda
  • 558
  • 5
  • 12