jjyoh
jjyoh

Reputation: 446

Find a more efficient way to code an If statement in python

it's the second time I'm confronted to this kind of code :

    if "associé" in gender or "gérant" in gender or "président" in gender or "directeur" in gender:
    gen = "male"
elif "associée" in gender or "gérante" in gender or "présidente" in gender or "directrice" in gender:
    gen = "female"
else:
    gen = "error"

I'd like to find a more efficient way to write this code because it looks really bad.

Upvotes: 2

Views: 71

Answers (3)

elethan
elethan

Reputation: 17003

I personally like doing this with sets. For example:

opts = ["associé", "gérant", "président", "directeur"]


if set(opts) & set(gender):
...

& is used for the set intersection operation which returns a new set with the items shared by the sets on either side of the &. This will execute the if block only if there is overlap in gender and opts. You can repeat the process for your elif as well, creating a list of the possible options and checking for overlap between that list and gender. All together, you could do something like this:

male_opts = ["associé", "gérant", "président", "directeur"]
female_opts = ["associée", "gérante", "présidente", "directrice"]

if set(male_opts) & set(gender):
    gen = "male"
elif set(female_opts) & set(gender):
    gen = "female"
else:
    gen = "error"

Also, as @Copperfield points out. You could increase efficiency even more by making the *_opt variables (and potentially even gender sets to begin with:

male_opts = {"associé", "gérant", "président", "directeur"}
female_opts = {"associée", "gérante", "présidente", "directrice"}
gender = set(gender)

if male_opts & gender:
...

Edit:

The code above assumes that gender is an iterable, but it seems from the comments that it is a string instead (e.g., 'associé gérant'. Although the accepted answer is better at this point, you could still use this solution by making gender a set of the words that make up the string:

gender = set(gender.split())

Upvotes: 4

Daniel
Daniel

Reputation: 42778

Using lists and any:

males = ["associé", "gérant", "président", "directeur"]
females = ["associée", "gérante", "présidente", "directrice"]

if any(m in gender for m in males):
    gen = "male"
elif any(m in gender for m in females):
    gen = "female"
else:
    gen = "Error"

Upvotes: 4

OneCricketeer
OneCricketeer

Reputation: 191983

If you cannot have multiple of these stings in one gender string, maybe something like this?

gen = "error"
for g in ["associé", "gérant", "président", "directeur"]:
    if g in gender:
        gen = "male"
        break
for g in ["associée" "gérante", "présidente", "directrice"]:
    if g in gender:
        gen = "female"
        break

Upvotes: 0

Related Questions