在另一个列表中查找包含5个连续字符串的单词

2024-09-30 08:25:24 发布

您现在位置:Python中文网/ 问答频道 /正文

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]进行比较。但我不知道怎么做


Tags: theinpos列表forifchecker单词
3条回答

如果目的只是识别由五个连续、重叠的州邮政缩写组成的单词,您可以尝试以下方法:

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']

def check_word(word):
    if len(word) != 7:
        return False
    counter = 0
    for i in range(0, len(word) - 1):
        abv = word[i] + word[i + 1]
        if abv in states:
            counter += 1
            if counter == 5:
                return True
        else:
            counter = 0
    return False


for w in wordList:
    print("{0} : {1}".format(w, check_word(w)))

与其使用st in word,不如使用word.find( st ),它将返回匹配的索引,或者-1。然后只需存储找到的索引

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']
    found_list = []
    for st in states:
        position = word.find( st )
        if ( position != -1 ):
            found_list.append( ( st, position ) )  # <  Keep the word + position
    if ( len( found_list ) >= 5 ):
        print("[%s]: " % ( word ) )
        for state, position in found_list:
            print( "   \"%s\" at %d" % ( state, position ) )


for word in [ 'marine', 'desert', 'dessert', 'icecream', 'chocolate', 'ohmmeter', 'comically' ]:
    puzzleH( word )

其中:

$ python3 ./state_find.py 
[marine]: 
   "ar" at 1
   "in" at 3
   "ma" at 0
   "ne" at 4
   "ri" at 2

编辑:针对Linux字典文件进行测试:

words = open( '/usr/share/dict/words.pre-dictionaries-common', 'rt' ).read().split('\n')
for word in words:
    if ( word.find( "'" ) == -1 ):
        puzzleH( word )

给出了很多结果:

# (just the tail ...)
[windowpane]: 
   "in" at 1
   "ne" at 8
   "nd" at 2
   "pa" at 6
   "wi" at 0
[windowpanes]: 
   "in" at 1
   "ne" at 8
   "nd" at 2
   "pa" at 6
   "wi" at 0
[windstorms]: 
   "in" at 1
   "ms" at 8
   "nd" at 2
   "or" at 6
   "wi" at 0
[windward]: 
   "ar" at 5
   "in" at 1
   "nd" at 2
   "wa" at 4
   "wi" at 0

哦,“调情”是个好词:

[philandering]: 
   "de" at 6
   "hi" at 1
   "il" at 2
   "in" at 9
   "la" at 3
   "nd" at 5
   "ri" at 8

编辑:它似乎没有像我应该读的那样完全阅读规范。单词需要完全重叠的状态代码组成

这里有一个版本可以解决这个问题。它从输入字中创建成对的字母,查找要匹配的状态代码,如果找到,则记录位置和状态代码(与以前相同)

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']
    found_list = []
    word_position = 0
    for i in range( len( word ) - 1 ):
        two_letters = word[i] + word[i+1]
        if ( two_letters in states ):
            found_list.append( ( two_letters, i ) )
        else:
            found_list = []
            break # word needs to be made of all state-codes

    if ( len( found_list ) >= 5 ):
        print("[%s]: " % ( word ) )
        for state, position in found_list:
            print( "   \"%s\" at %d" % ( state, position ) )

words = open( '/usr/share/dict/words.pre-dictionaries-common', 'rt' ).read().split('\n')

for word in words:
    if ( word.find( "'" ) == -1 ):
        puzzleH( word )

它发现的最长的是:

[malarial]: 
   "ma" at 0
   "al" at 1
   "la" at 2
   "ar" at 3
   "ri" at 4
   "ia" at 5
   "al" at 6

有趣的是,在整个73000个单词的字典中只有4个单词(>;=5个代码)

您可以创建一个dict,将状态缩写映射到索引,然后通过压缩给定单词的相邻字母对(偏移量为1),在dict中查找字母对,如果找到,则将相应的索引添加到输出列表:

state_indices = {state: index for index, state in enumerate(states)}
def puzzleH(word):
    indices = []
    for pair in zip(word, word[1:]):
        candidate = ''.join(pair)
        if candidate not in state_indices:
            break
        indices.append(state_indices[candidate])
    else:
    return indices

for word in wordList:
    indices = puzzleH(word)
    if indices is not None:
        print(word, indices)

相关问题 更多 >

    热门问题