Skip to content

Instantly share code, notes, and snippets.

@heath
Created July 22, 2013 21:46
Show Gist options
  • Save heath/6058003 to your computer and use it in GitHub Desktop.
Save heath/6058003 to your computer and use it in GitHub Desktop.
"""
License: MIT
Author: Heath Matlock
Problem: https://en.wikipedia.org/wiki/Weasel_program
"""
import string
import random
from time import time
class Typing_Monkey():
def __init__(self):
self.possible_choices = string.lowercase + ' '
self.desired_list = list('methinks it is a weasel')
self.prev_list_validity = []
def gen_string(self, length):
random_text = ''.join(random.choice(self.possible_choices) for _ in range(length))
return random_text
def check_validity(self, aList, desired_list):
if len(self.prev_list_validity) != 0:
# use assignment
for index, char in enumerate(aList):
if char == desired_list[index]:
self.prev_list_validity[index] = True
else:
self.prev_list_validity[index] = False
else:
# use append
for index, char in enumerate(aList):
if char == desired_list[index]:
self.prev_list_validity.append(True)
else:
self.prev_list_validity.append(False)
def gen_orig_list(self):
self.current_list = list(self.gen_string(len(self.desired_list)))
def gen_new_list(self):
new_list = []
for index, char in enumerate(self.prev_list_validity):
if char == True:
try:
# should succeed after the first attempt, using current_list
new_list.append(self.current_list[index])
except:
# should fall through the first attempt, using original_list
new_list.append(self.original_list[index])
else:
new_list.append(self.gen_string(1))
self.current_list = new_list
def bootstrap(self):
self.gen_orig_list()
self.check_validity(self.current_list, self.desired_list)
def start_typing(self):
starting_time = time()
self.bootstrap()
self.attempts = 1
while self.current_list != self.desired_list:
self.gen_new_list()
self.check_validity(self.current_list, self.desired_list)
self.attempts += 1
ending_time = time()
print "desired string: ", ''.join(self.desired_list)
print "resulting string: ", ''.join(self.current_list)
print "time elapsed: ", ending_time - starting_time
print "number of attempts: ", self.attempts
#######################################################
# Go monkey go!
#######################################################
if __name__ == '__main__':
typing_monkey = Typing_Monkey()
typing_monkey.start_typing()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment