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


given list of strings, return count of number of strings string length 3 or more , first , last chars of string same.

to solve problem created following function,

def match_ends(words):   firstl=words[0:1]   lastl=words[-1:]   x=len(words)>3 , firstl == lastl   count=0  x in words:     count+=1     return count 

then tested here,

def test(got, expected):   if got == expected:     prefix = ' ok '   else:     prefix = '  x '   print ('%s got: %s expected: %s' % (prefix, repr(got), repr(expected)))   # calls above functions 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 use list comprehension. list comprehension has 3 parts:

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

so example, can say

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

which produce list

[0 1 4 9 16] 

we can add third (filtering) line, , odd numbers back:

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

in particular case, don't care transformation part. want output word if fits criteria:

[word  word in word_list  if len(word) >= 3 , word[0] == word[-1] ] 

this give list back. need length of list:

len( [word  word in word_list  if len(word) >= 3 , word[0] == word[-1] ]  ) 

want turn function? here go:

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

Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -