0

Pretty noobie, but I'm trying to write a function that prints all the plural words in a list of words

So output would be:

 >>> printPlurals(['computer', 'computers', 'science,', 'sciences'])
 computers
 sciences

and this is what I have so far but I'm not getting any output. Any help would be great. ty.

def printPlurals(list1):
    plural = 's'

    for letter in list1:
        if letter[:-1] == 's':
            return list1
yummyyenni
  • 23
  • 7

3 Answers3

1

You're really close, but you're mixing a few things up. For starters, you don't need to have the plural variable. You're not using it anyway. Secondly, from a naming standpoint, it doesn't matter that you've named the variable letter as you have, but it implies that maybe you think you're looping through letters. Since you're actually looping through the members of the list list1, you're considering a word at each iteration. Finally, you don't want to return the list. Instead, I think you want to print the word that has been confirmed to end in s. Try the following. Good luck!

def print_plurals(word_list):
    for word in word_list:
        if word[-1] == 's':
            print word

In case you're interested in doing something a little more interesting (or "Pythonic", arguably), you could form the list of plurals through a list comprehension as follows:

my_list = ['computer', 'computers', 'science', 'sciences']
plural_list = [word for word in my_list if word[-1]=='s']
Nicholas Flees
  • 1,943
  • 3
  • 22
  • 30
1

Have you considered using the Python inflect library?

p = inflect.engine()
words = ['computer', 'computers', 'science', 'sciences']
plurals = (word for word in words if p.singular_noun(word))
print "\n".join(plurals)

It might seem strange to check if p.singular_noun since you asked for the plural values, but it makes sense when you consider that p.singular_noun(word) returns False when word is already singular. So you can use it to filter the words that are not singular.

kojiro
  • 74,557
  • 19
  • 143
  • 201
  • I haven't actually. I just started learning python and not in the advance stage yet, but it's very nice to know different methods I'm not familiar with such as that one! Thank you! – yummyyenni Oct 24 '14 at 03:26
0

A one liner way to do this is

def printPlurals(list1):
    print [word for word in list1 if word[-1]=='s']

Your main issue is that letter[:-1] will return everything up to the last letter. For just the last letter use [-1]. You also were returning values and not printing. You can either just fix those two issues, or use the one liner in this answer.

So your code fixed is:

def printPlurals(list1):
    plural = 's' #you don't need this line, as you hard coded 's' below

    for letter in list1:
        if letter[-1] == 's':
            print list1
Parker
  • 8,539
  • 10
  • 69
  • 98