I was given the task: I needed to create two small functions that give equal chances to “heads” or “tails” and, similarly to 6 dice, 1,2,3,4, 5 or 6.
Important: I could not use randint or similar functions for this purpose.
So, I created those two functions that generate a "pseudo-random number" using the time function (the first digit of milliseconds) from the python library:
import time
def dice():
ctrl = False
while ctrl == False:
m = lambda: int(round(time.time() * 1000))
f = m()
d = abs(f) % 10
if d in range(1,7):
return d
ctrl = True
def coin():
m = lambda: int(round(time.time() * 1000))
f = m()
if f % 2 == 0:
return "Tails"
elif f == 0:
return "Tails"
else:
return "Heads" (EDIT: I don't know why i typed "Dimes" before)
However, I observed a tendency to give “Tails” over “Heads”, so I created a function to check the percentage of “Tails” and “Heads” in 100 throws:
def _test():
ta = 0
he = 0
x = 100
while x > 0:
c = coin()
if c == "Tails":
ta += 1
else:
he += 1
x -= 1
time.sleep(0.001)
print("Tails:%s Heads:%s" % (ta, he))
The test result was (several times):
Tails:56 Heads:44
So, I did the same with the cubes function, and the result was:
1:20 2:20 3:10 4:20 5:10 6:20
, , - - - - - "3" "5" (, , ), , "0" "7".
.
EDIT:
round() m = lambda: int(round(time.time() * 1000)) - .