Home > Blockchain >  can't loop more than once - for loop (python)
can't loop more than once - for loop (python)

Time:12-30

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']

CodePudding user response:

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'))

CodePudding user response:

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

CodePudding user response:

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.

  • Related