Prometheus
Prometheus

Reputation: 33625

Python work out difference to 0

A user can only gain 100 points in a day. If the user gains more than 100 points I only want the value of delta to be the difference for example...

If a user has 100 (current_rep) and adds 10, then I want delta = 0

If a user has 90 (current_rep) and adds 20, then I want delta = 10

This is what I have so far:

REPUTATION_MAX_GAIN_PER_DAY = 100
current_rep = self.model.objects.calculate_points_for_today(user)
expected_rep = reputation_value + current_rep

if expected_rep > REPUTATION_MAX_GAIN_PER_DAY:
   delta = REPUTATION_MAX_GAIN_PER_DAY - current_rep

But above gives delta as a - not the allowed points.

Upvotes: 0

Views: 84

Answers (2)

Abhijit
Abhijit

Reputation: 63737

By changing the condition you can make it work, but to make it more readable use the built-in min

REPUTATION_MAX_GAIN_PER_DAY = 100
current_rep = self.model.objects.calculate_points_for_today(user)
expected_rep = min(reputation_value + current_rep, REPUTATION_MAX_GAIN_PER_DAY )
delta = expected_rep - current_rep

For the sake of completeness, here is the conditional statement that will work for you

if expected_rep > REPUTATION_MAX_GAIN_PER_DAY:
   expected_rep = REPUTATION_MAX_GAIN_PER_DAY
delta = expected_rep - current_rep

Upvotes: 3

Nathan Tregillus
Nathan Tregillus

Reputation: 6334

your if condition is backwards.

i think you mean to do:

if expected_rep <= REPUTATION_MAX_GAIN_PER_DAY:
   delta = REPUTATION_MAX_GAIN_PER_DAY - current_rep

Upvotes: 0

Related Questions