Sunday, March 29, 2009

Python: Random numbers

(link to webpage)


>>> random.random() # Random float x, 0.0 <= x <>
0.37444887175646646
>>> random.uniform(1, 10) # Random float x, 1.0 <= x <>
1.1800146073117523
>>> random.randint(1, 10) # Integer from 1 to 10, endpoints included
7
>>> random.randrange(0, 101, 2) # Even integer from 0 to 100
26
>>> random.choice('abcdefghij') # Choose a random element
'c'

>>> items = [1, 2, 3, 4, 5, 6, 7]
>>> random.shuffle(items)
>>> items
[7, 3, 2, 5, 6, 4, 1]

>>> random.sample([1, 2, 3, 4, 5], 3) # Choose 3 elements
[4, 1, 5]

---------------------------------
Using the Random Module
(link)
>>>
import random

>>> # 0.0 <= float <>
>>> random.random()
0.41360177662769904

>>> # 10.0 <= float <>
>>> random.uniform(10,20)
15.743669918803288

>>> # 10 <= int <= 20 (can be 20)
>>> random.randint(10,20)
10

>>> # 10 <= int < step="2) random.randrange(10,20,2)
16

>>> # choose from a list
>>> random.choice([1, 2, 3, 5, 9])
2

>>> # make a list into random order
>>> cards = range(52)
>>> random.shuffle(cards) # order is random now
>>> cards[:5] # get 5 cards
[37, 14, 42, 44, 6]
-------------------------------------------