As part of a study exercise I wrote a procedural script and would like to ask whether anyone has a more polished version. Your version can be procedural or object oriented.

#! /usr/bin/env python3

# This script simulates a monkey on a typewriter trying to come up with one sentence of Shakespeare
# Only the lowercase alpha characters are used and the sentence is "methinks it is like a weasel"
# WARNING! This script can cause out of memory system errors on thin computers! Use with caution!

import random

def createSentence():
    '''Generates and returns a random string of 27 characters'''
    seed = " abcdefghijklmnopqrstuvwxyz"
    output = ""
    for x in range(27):
        char = seed[random.randrange(0, 27)]
        output = output + char
    return output

def compareSentences():
    '''Compares the random string with the test string and returns the random string
       Returns a float as index of matching characters'''
    a = "methinks it is like a weasel"
    b = createSentence()
    counter = 0
    for x in range(len(a)-1):
        if b[x] == a[x]:
            counter = counter + 1
    return b, counter / 27 * 100

def recur():
    '''Prints number of iterations (in 000s), best match so far, and best match percentage
       Returns "Success!" in case of perfect match else runs indefinitely.'''
    counter = 0
    counter2 = 0
    storedSentence = ""
    b = False
    while not b:
        c, d = compareSentences()
        if d > counter2:
            storedSentence = c
            counter2 = d
        counter = counter + 1
        if counter % 1000 == 0:
            print(counter, storedSentence, counter2)
    print("Success!")

def main():
    recur()

if __name__ == "__main__":
    main()

Here is a version using generators.

#!/usr/bin/env python3

"""This script simulates a monkey on a typewriter trying to come up
with one sentence of Shakespeare.

Only the lowercase alpha characters are used and the sentence
is "methinks it is like a weasel"
"""

import random
import string

TEST_STRING = "methinks it is like a weasel"

def ape_sentences():
    """Generate an infinite sequence of random sentences"""
    alphabet = string.ascii_lowercase + " "
    a = len(alphabet)
    n = len(TEST_STRING)
    while True:
        yield ''.join(alphabet[random.randrange(a)] for i in range(n))

def evaluate(sentence):
    """Evaluates the proportion of characters in
    sentence which match characters in the test sentence"""
    r = sum(x == y for (x, y) in zip(sentence, TEST_STRING))
    return r / len(TEST_STRING)

def best_sentences():
    """Generate an infinite sequence of the best sentences
    written by the ape so far.
    """
    best_pair = (0, '')
    for s in ape_sentences():
        best_pair = max(best_pair, (evaluate(s), s))
        yield best_pair

def display(itercnt, sentence, score):
    """Print a number of iterations so far, the best sentence
    and the score of the best sencence.
    """
    print("{:<7} {} {:.4%}".format(str(itercnt), repr(sentence), score))

def main():
    """Simulate the sequence of ape's trials.
    """
    for i, (score, s) in enumerate(best_sentences(), 1):
        if s == TEST_STRING:
            display(i, s, score)
            print('SUCCESS!')
            break
        if i % 1000 == 0:
            display(i, s, score)

if __name__ == "__main__":
    main()

Edited 2 Years Ago by Gribouillis

This question has already been answered. Start a new discussion instead.