B_Furtado B_Furtado - 3 months ago 6
Python Question

Truncating a random gammavariate result to an upper limit

I want to draw a number from a gammavariate, but I want to set an upper limit.
Why this does not work?

import random
[int(random.gammavariate(3, 3)) if x < 21 else 20 for x in range(1)]

Out[59]: [22]


Thanks.

Answer

Why making things complicated?

x is always 0 in your list comprehension.

try it this way:

x = int(random.gammavariate(3,3))
[x if x < 21 else 20]