给定两个字符串作为参数返回true如果第一个字可以通过改变一个字母从第二个字形成.我接近这个的方式是:
def differ(word_one, word_two): '''(str, str) -> bool Returns true iff word_two can be formed from word_one by changing exactly one letter. >>> differ('cat', 'bat') True >>> differ('word', 'sword') False ''' temp_list = [] # If the length of the first string is equal to the length of the # second string, iterate over the letters in the first string and # if the letter in the first string does not equal to the letter # in the second string append the letter to temp_list if len(word_one) == len(word_two): for char in word_one: if char != word_two[word_one.index(char)]: temp_list.append(char) if len(temp_list) == 1: return True else: return False
根据描述,我的代码似乎工作得很好,但有一个更简化的方法吗?