Python3,这是蒙特卡洛时间!
为了解决这个问题,我首先计算一下您需要使用默认键盘(最初是:)进行多少次“点击” abc,def,ghi,jkl,mno,pqrs,tuv,wxyz
。然后,我修改此键盘,看看它是否更便宜(单击较少的文字即可)。如果此键盘便宜,则它将成为默认键盘。我重复此过程1M
时间。
要更改键盘,我首先确定要进行的更改(更改的最大数量是键盘中字母的总数)。然后,对于每个开关,我选择两个按钮和两个位置,然后将字符从第一个位置转移到第二个位置。
每次最多可切换的次数是键盘中字母的数目,因为它是您需要从两个完全不同的键盘切换的最少变更次数。(我希望始终可以从一个键盘切换到其他键盘)
输出 echo "jackdawslovemybigsphinxofquartz" | python .\myscript.py
为:
61 ['anb', 'sef', 'hjc', 'iykl', 'odm', 'qgr', 'tuxv', 'wpz']
61
组成给定消息所按的按钮数量在哪里。
字符(无空格,无注释):577
我知道它的时间很长,但是我真的是新手。
from random import *
S=['abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']
def P(L): # perform a switch of the keys of the keyboard:to switch from a given keyboard to another, the maximum number of exchanges is the number of the keys.
R=randint
N = len(''.join(L))
W = randint(1,N) # decide how many switches to perform
EL = list(L)
for i in range(0,W):
B1=R(0,len(EL)-1) # decide what buttons are considered in the switch
B2=R(0,len(EL)-1)
if len(EL[B1])==0: continue
P1=R(0,len(EL[B1])-1) # decide what letter to switch and where
if len(EL[B2])==0: P2=0
else: P2=R(0,len(EL[B2])-1)
C1 = EL[B1][P1]
EL[B1]=EL[B1].replace(C1,'')
EL[B2]=EL[B2][:P2]+C1+EL[B2][P2:]
return EL
def U(L,X): # count how many clicks you need to compose the text X
S=0
Z=' '
for A in X:
for T in L:
if A in T and Z not in T: S+=1+T.index(A)
if A in T and Z in T: S+=3+T.index(A) # if the last character was in the same button..here the penality!
Z=A
return S
X=input()
n_iter=10**6
L = list(S)
cc=U(L,X)
print(cc,L)
for i in range(0,n_iter): #do some montecarlo stuff
cc=U(L,X)
pl=P(L)
pc=U(pl,X)
if(cc>pc):
L=pl
print(pc,L)
我觉得很有趣,因此决定与LO HOBBIT一起尝试此算法(我也有原始副本!)。它有383964
字母,这些是我发现的几次点击与键盘:
909007 ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
879344 ['abkc', 'def', 'gqhi', 'jl', 'mno', 'rs', 'tupv', 'wxyz']
861867 ['abg', 'def', 'qhyi', 'jcl', 'mno', 'r', 'tupxv', 'swkz']
851364 ['abg', 'e', 'qchi', 'jyl', 'mn', 'dr', 'tupxv', 'sowkfz']
829451 ['ag', 'ef', 'qchi', 'jyl', 'mn', 'dbr', 'tupxv', 'sowkz']
815213 ['amg', 'ef', 'qch', 'ojyl', 'i', 'dbnr', 'tupxv', 'swkz']
805521 ['amg', 'ef', 'ch', 'ojyl', 'qi', 'dbnr', 'tupxv', 'swkz']
773046 ['amg', 'ef', 'ch', 'ojyl', 'qi', 'bnr', 'tupxv', 'dswkz']
759208 ['amg', 'eqf', 'ch', 'ojyl', 'i', 'bnr', 'tupxv', 'dswkz']
746711 ['ag', 'ekq', 'clh', 'sojy', 'bi', 'nmfr', 'tupxv', 'dwz']
743541 ['ag', 'ekq', 'clh', 'sojy', 'bi', 'nmfr', 'tpxv', 'dwuz']
743389 ['ag', 'ekq', 'clh', 'sojy', 'i', 'nmfr', 'tpxbv', 'dwuz']
734431 ['ag', 'ekq', 'lh', 'sjy', 'ci', 'nrf', 'tpxbv', 'dowumz']
705730 ['ag', 'oekq', 'lh', 'sjy', 'ci', 'nrf', 'tpxbv', 'dwumz']
691669 ['ag', 'oekq', 'lh', 'nsjy', 'ic', 'rf', 'tpxbv', 'dwumz']
665866 ['ag', 'hokq', 'el', 'nsjy', 'ic', 'rbf', 'tpxv', 'dwumz']
661610 ['agm', 'hokq', 'e', 'nsj', 'ilc', 'rbf', 'tpyxv', 'dwuz']
因此,我认为这最后一个是最实用的键盘之一(按点击次数)。