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()