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

最近通过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伐。

Antworte allen(2)
小葫芦

应该多利用 list comprehension

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

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

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!