I know that random is not truly random, but my test has a massively different result than the calculated probability.
Please find the error if there is one.
Below code is generating a string of length 3 out of 62 choices and at what point it repeates. The probability I calculated of repeating is 238.328 or 62^3.
Wen I run my code it repeats on average after 615 times.
import random
import string
def get_random_string(length):
choices = string.ascii_letters + string.digits
result_str = ''.join(random.choice(choices) for i in range(length))
return result_str
def main():
global repeated
results = []
for i in range(100000):
tmpstr = get_random_string(3)
if tmpstr in results:
print(f"it took {i} times to repeate.")
repeated.append(i)
break
else:
results.append(tmpstr)
if __name__ == "__main__":
print(len(string.ascii_letters + string.digits))
repeated = []
for i in range(10):
main()
print(sum(repeated)/len(repeated))
print("done")
Aucun commentaire:
Enregistrer un commentaire