無限猴子定理


無限猴子定理:猴子在打字機鍵盤上隨機敲擊鍵無限時間幾乎肯定會輸入一個給定的文本,例如威廉·莎士比亞的全集。


 

題目:使用python當作猴子,用python隨機生成給定的一句話需要多久。模擬方法為:

第一個函數:生成指定長度的隨機字符串。

第二個函數:將隨機生成的字符串與目標字符串進行比較,給出相似度。

第三個函數:重復多次后給出相似度最高的字符串。

目前寫的程序如下:

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 = None
    best_time = None
    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)

 

內容來源於最近在看一本關於Python數據結構和算法的書籍《Problem Solving with Algorithms and Data Structures using Python》,挺有意思的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM