In [1]:
import random
for i in range(5):
print('%04.3f' % random.random(), end=' ')
print()
In [2]:
import random
for i in range(5):
print('{:04.3f}'.format(random.uniform(1, 100)), end=' ')
print()
In [3]:
import random
random.seed(1)
for i in range(5):
print('{:04.3f}'.format(random.random()), end=' ')
print()
In [4]:
import random
random.seed(1)
for i in range(5):
print('{:04.3f}'.format(random.random()), end=' ')
print()
In [5]:
import random
import os
import pickle
if os.path.exists('state.dat'):
# Restore the previously saved state
print('Found state.dat, initializing random module')
with open('state.dat', 'rb') as f:
state = pickle.load(f)
random.setstate(state)
else:
# Use a well-known start state
print('No state.dat, seeding')
random.seed(1)
# Produce random values
for i in range(3):
print('{:04.3f}'.format(random.random()), end=' ')
print()
# Save state for next time
with open('state.dat', 'wb') as f:
pickle.dump(random.getstate(), f)
# Produce more random values
print('\nAfter saving state:')
for i in range(3):
print('{:04.3f}'.format(random.random()), end=' ')
print()
In [7]:
import random
print('[1, 100]:', end=' ')
for i in range(3):
print(random.randint(1, 100), end=' ')
print('\n[-5, 5]', end=' ')
for i in range(3):
print(random.randint(-5, 5), end=' ')
print()
In [8]:
import random
for i in range(3):
print(random.randrange(0, 101, 5), end=' ')
print()
In [9]:
import random
import itertools
outcomes = {
'heads': 0,
'tails': 0,
}
sides = list(outcomes.keys())
for i in range(10000):
outcomes[random.choice(sides)] += 1
print('Heads:', outcomes['heads'])
print('Tails:', outcomes['tails'])
In [12]:
import random
with open('random.ipynb', 'rt') as f:
words = f.readlines()
words = [w.rstrip() for w in words]
for w in random.sample(words, 5):
print(w)
In [13]:
import random
import time
print('Default initializiation:\n')
r1 = random.SystemRandom()
r2 = random.SystemRandom()
for i in range(3):
print('{:04.3f} {:04.3f}'.format(r1.random(), r2.random()))
print('\nSame seed:\n')
seed = time.time()
r1 = random.SystemRandom(seed)
r2 = random.SystemRandom(seed)
for i in range(3):
print('{:04.3f} {:04.3f}'.format(r1.random(), r2.random()))