在Python下,如何将一个单词,例如,“hello”,进行变种(mutate)?
伊谢尔伦
伊谢尔伦 2017-04-17 17:23:32
0
2
363

最近通过http://anandology.com/python-practice-book/working-with-data.html上的问题练习Python,做到章节2.6-列表第32个问题的时候,写出了以下代码,是否有更好的代码,可以解决这个问题。原问题如下:

Problem 32: Write a function mutate to compute all words generated by
a single mutation on a given word. A mutation is defined as inserting
a character, deleting a character, replacing a character, or swapping
2 consecutive characters in a string. For simplicity consider only
letters from a to z.

我的代码如下:

#coding:utf-8
def mutate(ori_word):
    result = []
    characters = [chr(w) for w in xrange(97,123)]
    split_word = [w for w in ori_word] #['h', 'e', 'l', 'l', 'o']
    for x in xrange(0,5):
        word = split_word[:]
        word.pop(x)
        result.append(''.join(word)) # delete any one of the character in "hello"
        for c in characters:
            word = split_word[:]
            word[x] = c
            result.append(''.join(word)) # replace any one of the character in "hello" by using a to z
        for y in xrange(0,5):
            word = split_word[:]
            word[x] , word[y] = word[y], word[x]
            result.append(''.join(word)) # swap two character in "hello"
    return result

word = mutate("hello")
伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回覆(2)
小葫芦

應該多利用 list comprehension

for x in xrange(0,5) 這些應該避免使用for x in xrange(0,5) 这些应该避免使用

split_word = [w for w in ori_word] 有点多此一举了 因为可以直接 iterate through 一个 str

split_word = [w for w in ori_word] 有點多此一舉了 因為可以直接 iterate through 一個 str

我的答案:🎜
def mutate(word):
    return [
        value for i in range(len(word)) for letter in 'abcdefghijklmnopqrstuvwxyz' for value in [
            word[:i+1]+word[i+2:i:-1]+word[i+3:], # swap
            word[:i]+letter+word[i:], # insert
            word[:i]+letter+word[i+1:], # replace
            word[:i]+word[i+1:] # remove (duplicated)
        ]
    ]
巴扎黑

來學習真·大神的寫法:

How to Write a Spelling Corrector

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!