HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythondjangoMinor

Code efficiency with many records

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withrecordsmanycodeefficiency

Problem

I have a bunch of functions that return strings based upon score ranges. Then I have another function that sums everything up and assigns a numeric weight.

@property
def risk_status(self):
    """ This function assigns numeric weight to risks. It returns an over all integer score. """

    # Build a string of risks, ie "High Risk@At Risk@@Extreme Risk"
    raw_string_of_risks = self.si_risk + '@' + self.aggbs_risk + '@' + self.cfimb_risk + '@' + self.cfiab_risk + '@' + self.cei_risk

    # Build a list ["High Risk", "At Risk", "Extreme Risk"]
    risks = raw_string_of_risks.split('@')

    # Formula for over all risk status. ["High Risk", "At Risk", "Extreme Risk"] => 2+1+3 = 6
    status = risks.count("At Risk")*1 + risks.count("High Risk")*2 + risks.count("Extreme Risk")*3

    return status


I'm afraid with a gazillion records this property might slow things down. It will never get a string longer than 65 characters to parse, but will doing this over and over again really slow things down?

Solution

Concatenating an splitting seems like you're making extra work for yourself. I suggest summing the results of a string-to-integer translation.

from collections import defaultdict

_RISK_SCORE = defaultdict(int, [('Extreme Risk', 3), ('High Risk', 2), ('At Risk', 1)])

@property
def risk_status(self):
    """ This function assigns numeric weight to risks. It returns an overall integer score. """
    return sum(self._RISK_SCORE[r] for r in (
        self.si_risk,
        self.aggbs_risk,
        self.cfimb_risk,
        self.cfiab_risk,
        self.cei_risk,
    ))

Code Snippets

from collections import defaultdict

_RISK_SCORE = defaultdict(int, [('Extreme Risk', 3), ('High Risk', 2), ('At Risk', 1)])

@property
def risk_status(self):
    """ This function assigns numeric weight to risks. It returns an overall integer score. """
    return sum(self._RISK_SCORE[r] for r in (
        self.si_risk,
        self.aggbs_risk,
        self.cfimb_risk,
        self.cfiab_risk,
        self.cei_risk,
    ))

Context

StackExchange Code Review Q#46314, answer score: 3

Revisions (0)

No revisions yet.