1

What would be the best approach for the following...

In a Django I have a view with a variable called 'showItem' which could be true or false. I want to set showItem to true 40% of the time and false 60% of the time, with options to change these odds later on.

Using Python how should I go about this?

Part of view:

 def get_context_data(self, **kwargs):
        context = super(EntryDetail, self).get_context_data(**kwargs)
        context['showItem'] = (odds?????)
        return context
GrantU
  • 6,325
  • 16
  • 59
  • 89
  • 2
    Try `random.randrange(100) > 40` (http://stackoverflow.com/questions/14324472/random-boolean-by-percentage). – alecxe Aug 07 '13 at 08:12

2 Answers2

6

Here is another method:

import random

cur_num   = random.random()
threshold = 0.4

# showItem is true 60 % of the time
showItem = cur_num >= threshold

If you choose to change the threshold value later, you can just modify the threshold variable which is easier than the other methods listed.

2
import random
num = random.randint(0, 4)
context['showItem'] = True if num <= 1 else False

Here I think @Xaranke's answer is better and more flexible. I also test the performance of random and randint on my laptop, the former is 10x faster.

Chien-Wei Huang
  • 1,773
  • 1
  • 17
  • 27