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

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

reply all(2)
小葫芦

Should make more use of list comprehension

for x in xrange(0,5) These should be avoided 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] It’s a bit unnecessary because you can directly iterate through a str

My answer: #🎜🎜#
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)
        ]
    ]
巴扎黑

Let’s learn how to write Zhen·Da Shen:

How to Write a Spelling Corrector

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!