Jared Wright - 2 years ago 63
Python Question

# How to return the number of times a string with specific requirements appears in a list?

Given a list of strings, return the count of the number of strings where the string length is 3 or more and the first and last chars of the string are the same.
def match_ends(words):
FirstL=words[0:1]
LastL=words[-1:]
x=len(words)>3 and FirstL == LastL
count=0
for x in words:
count+=1
return count

Test

``````def test(got, expected):
if got == expected:
prefix = ' OK '
else:
prefix = '  X '
print ('%s got: %s expected: %s' % (prefix, repr(got), repr(expected)))

# Calls the above functions with interesting inputs.
def main():
print ('match_ends')
test(match_ends(['abaa', 'xyzax', 'aa', 'x', 'bbb']), 3)
test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 1)
test(match_ends(['aaa', 'be', 'abc', 'hello']), 1)

print
``````

Result:
X got: 1 expected: 3
OK got: 1 expected: 1
OK got: 1 expected: 1

Your best bet here is to use a list comprehension. A list comprehension has three parts:

• The transformation that you want to perform on each element of the input,
• the input itself, and
• an optional "if" statement that indicates when to produce output

So for example, we can say

```[ x * x # square the number for x in range(5) ] # for each number in [0,1,2,3,4]```

which will produce the list

`[0 1 4 9 16]`

We can add a third (filtering) line, and get only odd numbers back:

```[x * x for x in range(5) if x % 2] # divide x by 2, take the remainder -- if 1, output the number```

In your particular case, we don't care about the transformation part. We just want to output the word if it fits your criteria:

```[word for word in word_list if len(word) >= 3 and word[0] == word[-1] ]```

This will give you a list back. Now you just need to get the length of that list:

```len( [word for word in word_list if len(word) >= 3 and word[0] == word[-1] ] )```

Want to turn that into a function? Here you go:

```def count_matching_words(word_list): return len([word for word in word_list if len(word) >= 3 and word[0] == word[-1]])```

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download