I'm attempting to minimise the "duplicate" functions I have defined which do almost the exact same thing, but I'm unsure of the best way to do it, I thought of passing in the type I'm looking for (e.g. 1 for GreyLeader, 2 for HeadMarshal etc.) but that ended up looking too messy for my liking.
Could you guys perhaps suggest a way to combine the three functions into one to return the same result?
Some notes: - marshal is a list of a Marshal class which has Name, HeadMarshal, Marshal, GreyLeader boolean flags as properties - usedMarshals is a list of Marshals - each marshal can only be used twice, so the usedMarshals.count(marshal) = 2 is used for that
Code:
def get_marshal():
marshal = random.choice(marshals)
if marshal.Marshal:
if not marshal in usedMarshals:
return marshal
elif marshal in usedMarshals:
if usedMarshals.count(marshal) < 2:
return marshal
elif usedMarshals.count(marshal) >= 2:
return get_marshal()
elif not marshal.Marshal:
return get_marshal()
def get_head_marshal():
marshal = random.choice(marshals)
if marshal.HeadMarshal:
if not marshal in usedMarshals:
return marshal
elif marshal in usedMarshals:
if usedMarshals.count(marshal) < 2:
return marshal
elif usedMarshals.count(marshal) >= 2:
return get_head_marshal()
elif not marshal.HeadMarshal:
return get_head_marshal()
def get_grey_leader():
marshal = random.choice(marshals)
if marshal.GreyLeader:
if not marshal in usedMarshals:
return marshal
elif marshal in usedMarshals:
if usedMarshals.count(marshal) < 2:
return marshal
elif usedMarshals.count(marshal) >= 2:
return get_grey_leader()
elif not marshal.GreyLeader:
return get_grey_leader()
get_leader(kind): leader = random.choice( (m for m in marshals if isinstance(m, kind) ) )
I cannot test it without the marshal classes. Where kind ismarshal.Marshal
ormarshal.HeadMarshal
ormarshal.GreyLeader
\$\endgroup\$