This repository was archived by the owner on May 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtimeit-rand.py
More file actions
93 lines (69 loc) · 2.44 KB
/
timeit-rand.py
File metadata and controls
93 lines (69 loc) · 2.44 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
"""
Ce module vérifie que la distributions des nombres aléatoires
en Python est uniforme.
"""
import random
def frequence_rand_v0(maxint = 100, maxtry = 1000000):
"""
return a dict containing the frequence of random numbers
maxtin : takes numbers between 1 and maxint
maxtry : makes maxtry try
"""
L = []
for i in range(maxtry):
L.append(random.randint(1,maxint))
frequence = {}
for x in range(1,maxint+1):
frequence[x] = L.count(x)
#frequence = {x: L.count(x) for x in range(1, maxint+1)}
return frequence
def frequence_rand_v1(maxint = 100, maxtry = 1000000):
"""
return a dict containing the frequence of random numbers
maxtin : takes numbers between 1 and maxint
maxtry : makes maxtry try
"""
L = [random.randint(1,maxint) for i in range(maxtry)]
frequence = {}
for x in range(1,maxint+1):
frequence[x] = L.count(x)
#frequence = {x: L.count(x) for x in range(1, maxint+1)}
return frequence
def frequence_rand_v2(maxint = 100, maxtry = 1000000):
"""
return a dict containing the frequence of random numbers
This version does not create temporary lists, but only uses
iterators, it is more memory efficient.
maxtin : takes numbers between 1 and maxint
maxtry : makes maxtry try
"""
frequence = {}
for i in range(1,maxtry+1):
a_try = random.randint(1,maxint)
frequence[a_try] = frequence.setdefault(a_try, 0) + 1
return frequence
def frequence_rand_v3(maxint = 100, maxtry = 1000000):
"""
use the collections.Counter to count automatically
maxtin : takes numbers between 1 and maxint
maxtry : makes maxtry try
"""
import collections
# expression génératrice
L = (random.randint(1,maxint) for i in range(maxtry))
return collections.Counter(L)
def print_frequence(frequence):
"""
print the frequence of random numbers.
frequence : a dict returned by frequence_rand
"""
for k, v in frequence.items():
print(f'{k:>3} {v:>5}')
import timeit
if __name__ == '__main__':
print(f"v0: {timeit.timeit(stmt='frequence_rand_v0(30)', number=1, globals=globals())}s")
print(f"v1: {timeit.timeit(stmt='frequence_rand_v1(30)', number=1, globals=globals())}s")
print(f"v2: {timeit.timeit(stmt='frequence_rand_v2(30)', number=1, globals=globals())}s")
print(f"v3: {timeit.timeit(stmt='frequence_rand_v3(30)', number=1, globals=globals())}s")
d = frequence_rand_v0(30)
print_frequence(d)