-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomChoices.py
More file actions
133 lines (94 loc) · 2.27 KB
/
RandomChoices.py
File metadata and controls
133 lines (94 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 10 23:11:02 2021
@author: maherme
"""
#%%
import random
l = [10, 20, 30, 40, 50]
random_index = random.randrange(len(l))
l[random_index]
#%%
l = list(range(1000))
randoms = []
for _ in range(5):
randoms.append(l[random.randrange(len(l))])
print(randoms)
#%%
# A more pythonic way to do this:
randoms = []
for _ in range(5):
randoms.append(random.choice(l))
print(randoms)
#%%
# We can do using list comprehension, this a better option:
randoms = [random.choice(l) for _ in range(5)]
print(randoms)
#%%
# Probably the best way:
randoms = random.choices(l, k=5)
print(randoms)
#%%
# You can specify the weight of the choices:
l = ['a', 'b', 'c']
for _ in range(10):
print(random.choices(l, k=5))
print("-----------------------------------")
weights = [10, 1, 1]
l = ['a', 'b', 'c']
for _ in range(10):
print(random.choices(l, k=5, weights=weights))
#%%
from collections import namedtuple
Freq = namedtuple('Freq', 'count freq')
def freq_counts(lst):
total = len(lst)
return {k: Freq(lst.count(k), 100 * lst.count(k) / total) for k in set(lst)}
print(freq_counts(random.choices(l, k=100_000)))
#%%
weights = [8, 1, 1]
print(freq_counts(random.choices(l, k=100_000, weights=weights)))
#%%
cum_weights = [7, 8, 10]
print(freq_counts(random.choices(l, k=100_000, cum_weights=cum_weights)))
#%%
from time import perf_counter
random.seed(0)
denoms = random.choices([0, 1], k=10_000_000)
start = perf_counter()
for d in denoms:
if d == 0:
continue
else:
10 / d
end = perf_counter()
print(f'Avg elapsed time: {(end-start)/len(denoms):0.15f}')
start = perf_counter()
for d in denoms:
try:
10 / d
except ZeroDivisionError:
pass
end = perf_counter()
print(f'Avg elapsed time: {(end-start)/len(denoms):0.15f}')
#%%
random.seed(0)
denoms = random.choices([0, 1], k=10_000_000, weights=[1, 9])
start = perf_counter()
for d in denoms:
if d == 0:
continue
else:
10 / d
end = perf_counter()
print(f'Avg elapsed time: {(end-start)/len(denoms):0.15f}')
start = perf_counter()
for d in denoms:
try:
10 / d
except ZeroDivisionError:
pass
end = perf_counter()
print(f'Avg elapsed time: {(end-start)/len(denoms):0.15f}')
#%%