Infinite monkey theorem

Infinite monkey theorem: monkey randomly hitting keys on a typewriter keyboard unlimited time would almost certainly enter a given text, such as The Complete Works of William Shakespeare.


 

Topic: Using the python as a monkey, randomly generated with python how long a given word. Simulation methods are:

The first function: generating a random string of specified length.

The second function: a randomly generated character string is compared with the target string, given the similarity.

The third function: after repeating several times the highest degree of similarity is given string.

Currently written procedures are as follows:

import random

NUM = 1000
char_list = [chr(c+ord('a')) for c in range(26)]
char_list.append(' ')
target_list = 'hwnzy is a handsome boy'


def fun1():
    temp_list = []
    for index in range(27):
        temp_list.append(char_list[random.randint(0, 26)])
    return ''.join(temp_list)


def fun2(temp_list):
    score = 0
    for index in range(len(target_list)):
        if target_list[index] == temp_list[index]:
            score += 1
    return score


def fun3(times):
    best_score = -1
    best_time = -1
    best_list = []
    for index in range(times):
        temp_list = fun1()
        score = fun2(temp_list)
        if score > best_score:
            best_score = score
            best_time = index
            best_list = temp_list
        print('%dTH similarity is %.3f' % (index+1, score/len(target_list)))
    print("the best similarity is %dTH %.3f" % (best_time, best_score/len(target_list)))
    print(best_list)


if __name__ == '__main__':
    print(target_list)
    fun3 (NUM)

 

Content comes from recently reading a book on Python data structures and algorithms "Problem Solving with Algorithms and Data Structures using Python", very interesting.

Guess you like

Origin www.cnblogs.com/hwnzy/p/10927681.html