kevinSmith
kevinSmith

Reputation: 23

How to create a list from results from a given list within a for loop?

I am doing googles python class. And came across this problem:

# 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.

I tried different approaches, but cant seem to get it to work. This is what i got now:

def match_ends(words):
words=sorted(words, key=len)
for i in words:
    if len(i)<2:
        print(i)
        words=words[1:]
        print(words)
        for i in words:
            if i[0:2]==i[-2:]:
                x=[]
                x.append[i]

How is this done?

Upvotes: 0

Views: 114

Answers (4)

Call me Walter
Call me Walter

Reputation: 43

pretty much the same as previous answers, but lambda

match_ends = lambda ws: sum(1 for w in ws if len(w)>1 and w[0] == w[-1])

or 'expanded' form

match_ends = lambda words: sum(1 for word in words if len(word)>1 and word[0] == word[-1])

Upvotes: 0

fames
fames

Reputation: 46

You could simply do this:

def match_ends(words):
    count = 0

    for word in words:
        if len(word) >= 2 and word[0] == word[-1]:
            count += 1

    return count

Upvotes: 3

ruohola
ruohola

Reputation: 24087

Easy to accomplish using sum and a generator expression:

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

Upvotes: 5

ClimbingTheCurve
ClimbingTheCurve

Reputation: 333

A more pythonic solution might be

def func(s):
  return len(s) >= 2 and s[0] == s[-1]

str_list = ['applea', 'b', 'cardc']

filtered_list = [s for s in str_list if (len(s) >= 2 and s[0] == s[-1])]
# or 
filtered_list = list(filter(func, str_list))

count = len(filtered_list)

Upvotes: 0

Related Questions