(Python) How can I add characters to a certain string in a set?

Question:

I have some ideas on how to do this and I don’t really know how to approach it. I wrote up this code and it doesn’t seem to work, mainly because I don’t know how sets work. It’s supposed to take a list and if any of the strings are matching it will take that string and make it plural then add it to a set.

    newSet = set()

    for i in lst:
        if lst.count(i) > 1:
            newSet.add(i)
            "s".join(newSet)
        else:
            newSet.add(i)

    return newSet
Asked By: Xin

||

Answers:

Each str is immutable.
We can assign name = 'cow' and then
talk about name + 's', but that plural
string is a separate string object.
Appending 's' has no effect on the first string.

Better to populate the set with what you want
from the get go, rather than populating it
and then changing your mind.
That way there’s no need to remove singular
when you add plural to the set.

cf the docs.

from collections import Counter

animals = Counter(['cow', 'pig', 'cow', 'pig', 'sheep'])
print({name if count == 1 else f'{name}s'
       for name, count in animals.items()})

EDIT

The f-string computes name + 's'.

The set comprehension computes this:

s = set()
for name, count in animals.items():
    s.add(name)  # or if you prefer, an expression that pluralizes
print(s)
Answered By: J_H
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.