The word marine consists of five consecutive, overlapping state postal abbreviations: Massachusetts (MA), Arkansas (AR), Rhode Island (RI), Indiana (IN), and Nebraska (NE). Find a seven-letter word that has the same property.
我正在使用Python打开一个由大约5000个单词组成的列表。我想先找到一个包含5个州缩写的单词
def puzzleH(word):
states = ['al', 'ak', 'az', 'ar', 'ca', 'co', 'ct', 'dc', 'de', 'fl', 'ga',
'hi', 'id', 'il', 'in', 'ia', 'ks', 'ky', 'la', 'me', 'md',
'ma', 'mi', 'mn', 'ms', 'mo', 'mt', 'ne', 'nv', 'nh', 'nj',
'nm', 'ny', 'nc', 'nd', 'oh', 'ok', 'or', 'pa', 'ri', 'sc',
'sd', 'tn', 'tx', 'ut', 'vt', 'va', 'wa', 'wv', 'wi', 'wy']
checker = 0;
for st in states:
if st in word:
checker+=1
if checker==5:
# ...still thinking...
#pos = (i for i,st in enumerate(word) if st in states)
#for i in pos: print(i)
#return word
# Main program
ListH = []
for word in wordList:
if puzzleH(word)!=None:
ListH.append(puzzleH(word))
在找到一个包含5个州缩写的单词后,我将找到每个州缩写的索引。并将这些索引列表与[0,1,2,3,4]
或[1,2,3,4,5]
或[2,3,4,5,6]
进行比较。但我不知道怎么做
如果目的只是识别由五个连续、重叠的州邮政缩写组成的单词,您可以尝试以下方法:
与其使用
st in word
,不如使用word.find( st )
,它将返回匹配的索引,或者-1
。然后只需存储找到的索引其中:
编辑:针对Linux字典文件进行测试:
给出了很多结果:
哦,“调情”是个好词:
编辑:它似乎没有像我应该读的那样完全阅读规范。单词需要完全由重叠的状态代码组成
这里有一个版本可以解决这个问题。它从输入字中创建成对的字母,查找要匹配的状态代码,如果找到,则记录位置和状态代码(与以前相同)
它发现的最长的是:
有趣的是,在整个73000个单词的字典中只有4个单词(>;=5个代码)
您可以创建一个dict,将状态缩写映射到索引,然后通过压缩给定单词的相邻字母对(偏移量为1),在dict中查找字母对,如果找到,则将相应的索引添加到输出列表:
相关问题 更多 >
编程相关推荐