2014-05-21 47 views
-3

交替字是一個單詞,它的字母按照嚴格的順序交替排列,並按照與原始單詞相同的順序使用,構成至少兩個其他單詞。必須使用所有字母,但較小的單詞不一定具有相同的長度。例如,使用每個第二個字母的七個字母的單詞將產生四個字母的單詞和一個三個字母的單詞。這裏有兩個例子:交替字的Python代碼

「板」:使「壞」和「或」。 「腰」:使「機智」和「屁股」。 使用單詞列表http://www.puzzlers.org/pub/wordlists/unixdict.txt,編寫一個程序,遍歷列表中的每個單詞,並嘗試使用每個第二個字母製作兩個較小的單詞。較小的單詞也必須是列表中的成員。以上述方式將文字打印到屏幕上。

+0

你忘了提問了。 –

回答

0

你迄今試過的一些例子可能有所幫助,這不是家庭作業交換。

事實上,你可能要去有這個問題的手段傳給人,但由於它有點代碼高爾夫球這裏是它的快速黑客從我(未經測試)

def alternade(text, setAllWords): 
    """ returns a tuple containing the two words that form the alternade 
     or None if the word is not an alternade 
    """ 
    listA = []; 
    listB = []; 
    textLength = len(text); 
    # prevent selecting character out of range by ensuring string is even 
    if textLength % 2: 
     textLength += 1 
     text = text + " " 
    for i in range(0, len(text), 2): 
     listA.append(text[i]) 
     listB.append(text[i+1]) 
    strA = ''.join(listA).strip() 
    strB = ''.join(listB).strip() 

    if strA in setAllWords and strB in setAllWords: 
     return (strA, strB) 
    return None 

# To do populate this set with ALL words in source word list: 
setAllWords = set([ "ass", "bad", "or", "wit", "dog", "etc..." ]) 

print alternade("board", setAllWords) 
print alternade("waists", setAllWords) 
當然

,你會需要一組所有的單詞,而不僅僅是我在這裏展示的幾個單詞,並且要找到工作交叉表達式,您需要遍歷所有調用alternade()的單詞並忽略那些返回空列表的單詞。

alternade(...)也可以更改爲返回一個布爾值,而不是組成該字母的構成詞。

(我敢肯定有Python的大師那裏誰可以在一個更Python的方式重寫,但我還沒有真正使用Python的專業,現在幾年)

0

你可以試試下面的代碼:

f = open("http://www.puzzlers.org/pub/wordlists/unixdict.txt") 
for line in f: 
    line = line.strip() 
    length = len(line) 
    word1 = "" 
    word2 = "" 
    for i in range(0, length,2): 
     word1 += line[i] 
     try: 
      word2 += line[i+1] 
     except: 
      pass 
     word1 = word1.strip() 
     word2 = word2.strip() 
     print ("==>"), word1, ("and"), word2