最近通过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")
應該多利用 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
來學習真·大神的寫法:
How to Write a Spelling Corrector