我试图生成一个随机的字母序列,它应该等于一个特定的字符串。一个完全随机的迭代确实需要很长时间,所以我尝试了爬山的方法。它可以找到,直到目标和生成的句子的相似性几乎相同,但它从来没有达到100%。你知道这是什么问题吗?
import string
import random
sim = []
sen_list = []
def random_sen():
goal = "The value of the intrinsic motivation cannot be underestimated"
sen = []
i = 0
for i in range(len(goal)):
sen.append(random.choice(string.ascii_letters + ' '))
i += 1
sen = ''.join(sen)
sen = sen.lower()
return sen
def test_similarity(sen):
i = 0
# sen = random_sen()
sen = updating_sen(sen)
similarity_value = 0
goal = "The value of the intrinsic motivation cannot be underestimated"
for i in range(len(sen)):
if goal[i] == sen[i]:
similarity_value = similarity_value + 1
similarity_value = similarity_value/len(sen)
return similarity_value
def updating_sen(sen_max):
goal = "The value of the intrinsic motivation cannot be underestimated"
i = 0
sen = []
for i in range(len(goal)):
if goal[i] == sen_max[i]:
sen.append(goal[i])
else:
sen.append(random.choice(string.ascii_letters + ' '))
i += 1
sen = ''.join(sen)
sen = sen.lower()
return sen
def play():
counter = 1
sen_max = random_sen()
while(1):
sen = updating_sen(sen_max)
similarity_value = test_similarity(sen)
sim.append(similarity_value)
sen_list.append(sen)
if similarity_value == 1:
print("The monkey can call himself Shakespear now!! The sentence is %s" % (sen_max))
break
if similarity_value != 1:
counter = counter + 1
if counter % 10000 == 0:
sim_max = max(sim)
max_index = sim.index(sim_max)
sen_max = sen_list[max_index]
print ("Try number %d. This is the sim_max value: %s. The sentence is: %s" % (counter,sim_max, sen_max))
return sen_max
sen_max = play()
暂无答案!
目前还没有任何答案,快来回答吧!