Last active
March 1, 2020 11:30
-
-
Save typeswitch-dev/6616031843abb8823cd597522dc5b809 to your computer and use it in GitHub Desktop.
Approximates e using bogosort.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Calculates e using randomized bogosort. The average number | |
# of comparisons per round should be close to e-1 due to | |
# shortcircuiting, so we run bogosort and keep track of | |
# the number of rounds and number of comparisons, and use | |
# that to calculate e. | |
import random | |
n = 10 | |
xs = list(range(n)) # start with a sorted list to rub it in. | |
num_rounds = 0 | |
num_comparisons = 0 | |
done = False | |
while not done: | |
num_rounds += 1 | |
random.shuffle(xs) | |
done = True | |
for i in range(n-1): | |
num_comparisons += 1 | |
if xs[i] > xs[i+1]: | |
done = False | |
break | |
print('n:', n) | |
print('num_rounds:', num_rounds) | |
print('num_comparisons:', num_comparisons) | |
print('e:', 1 + num_comparisons/num_rounds) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample output: