C2_W1_Assignment Exercise 6

I watched the video of building the model again, still cannot find the rules to replace a character in a word. And I also couldn’t understand why the expected output is:

Input word = can 
split_l = [('', 'can'), ('c', 'an'), ('ca', 'n')] 
replace_l ['aan', 'ban', 'caa', 'cab', 'cac', 'cad', 'cae', 'caf', 'cag', 'cah', 'cai', 'caj', 'cak', 'cal', 'cam', 'cao', 'cap', 'caq', 'car', 'cas', 'cat', 'cau', 'cav', 'caw', 'cax', 'cay', 'caz', 'cbn', 'ccn', 'cdn', 'cen', 'cfn', 'cgn', 'chn', 'cin', 'cjn', 'ckn', 'cln', 'cmn', 'cnn', 'con', 'cpn', 'cqn', 'crn', 'csn', 'ctn', 'cun', 'cvn', 'cwn', 'cxn', 'cyn', 'czn', 'dan', 'ean', 'fan', 'gan', 'han', 'ian', 'jan', 'kan', 'lan', 'man', 'nan', 'oan', 'pan', 'qan', 'ran', 'san', 'tan', 'uan', 'van', 'wan', 'xan', 'yan', 'zan']

cause this is how i implement with a different output:

# UNIT TEST COMMENT: Candidate for Table Driven Tests
def replace_letter(word, verbose=False):
        word: the input string/word 
        replaces: a list of all possible strings where we replaced one letter from the original word. 
    letters = 'abcdefghijklmnopqrstuvwxyz'
    replace_l = []
    split_l = []
    ### START CODE HERE ###
    split_l = [(word[:i],word[i:]) for i in range(len(word))]
    replace = [a[:-1]+c+b[1:] for a,b in split_l if b for c in letters ]
    replace_set = set(replace)
    ### END CODE HERE ###
    # turn the set back into a list and sort it, for easier viewing
    replace_l = sorted(list(replace_set))
    if verbose: print(f"Input word = {word} \nsplit_l = {split_l} \nreplace_l {replace_l}")   
    return replace_l

could you please tell the replace rule.

Hi @Yufeng_Li1

When calculating replace, you unnecessary use [:-1].
Your code would work on the first split (because ''[:-1] is still '') and you would get:

[‘aan’, ‘ban’, ‘can’, ‘dan’, ‘ean’, ‘fan’, ‘gan’, ‘han’, ‘ian’, ‘jan’, ‘kan’, ‘lan’, ‘man’, ‘nan’, ‘oan’, ‘pan’, ‘qan’, ‘ran’, ‘san’, ‘tan’, ‘uan’, ‘van’, ‘wan’, ‘xan’, ‘yan’, ‘zan’]

But think what happens with the second split (('c', 'an')) - here 'c'[:-1] is equal to '', but it should be 'c' for correct replacements. In other words, your result is:

[‘an’, ‘bn’, ‘cn’, ‘dn’, ‘en’, ‘fn’, ‘gn’, ‘hn’, ‘in’, ‘jn’, ‘kn’, ‘ln’, ‘mn’, ‘nn’, ‘on’, ‘pn’, ‘qn’, ‘rn’, ‘sn’, ‘tn’, ‘un’, ‘vn’, ‘wn’, ‘xn’, ‘yn’, ‘zn’]

but should have been:

[‘can’, ‘cbn’, ‘ccn’, ‘cdn’, ‘cen’, ‘cfn’, ‘cgn’, ‘chn’, ‘cin’, ‘cjn’, ‘ckn’, ‘cln’, ‘cmn’, ‘cnn’, ‘con’, ‘cpn’, ‘cqn’, ‘crn’, ‘csn’, ‘ctn’, ‘cun’, ‘cvn’, ‘cwn’, ‘cxn’, ‘cyn’, ‘czn’]

Notice that you are missing the 'c' in the second split. Same thing with other splits.