Skip to content

Instantly share code, notes, and snippets.

@MrCreosote
Created June 22, 2022 22:33
Show Gist options
  • Save MrCreosote/b72a5dd0248b7a601a2944501a0b1fc0 to your computer and use it in GitHub Desktop.
Save MrCreosote/b72a5dd0248b7a601a2944501a0b1fc0 to your computer and use it in GitHub Desktop.
Stochastic measure of the sortedness of a list
import random
def stochastic_sortedness(list_, num_samples):
''' Based on https://stackoverflow.com/a/16994740/643675 '''
if len(list_) < 2:
return 0
# a 2 item list works, but is a pretty dumb thing to pass to this function *shrug*
maxindex = len(list_) - 1
score = 0
count = 0
while count < num_samples:
i1 = random.randint(0, maxindex)
i2 = random.randint(0, maxindex)
if i1 != i2:
score += 0 if list_[min(i1, i2)] <= list_[max(i1, i2)] else 1
count += 1
return score / num_samples
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment