[Solved] solution to this recursive function questions? [closed]


I understand the down-votes and the closing votes, since you don’t show the slightest effort here. On the other hand, this is a non-trivial problem. I will assume for a second that you are genuinely interested in a solution to this problem and I’ll show you how I would write this (without having looked too much at the code you posted).

lets=("", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz")

def trans(pnum, res = ""):           # res is the current result (initially the empty string)
    if not pnum:
        yield res                    # phone number is empty string, so we're done, return res
    else:
        digit = pnum[0]              # get first digit
        try:
            repls = lets[int(digit)] # if it is an integer, get replacements
            if not repls:            # if replacements is an empty string,
                repls = digit        #    fall back to initial digit
        except ValueError:
            repls = digit            # not an integer  - fall back to initial character
        for i in repls:              # for every replacement character
            yield from trans(pnum[1:], res+i) # recursively process the rest of the phone number

for pnum in ["borla63", "h3llo"]:
    print(list(trans(pnum)))

which yields

['borlamd', 'borlame', 'borlamf', 'borland', 'borlane', 'borlanf', 'borlaod', 'borlaoe', 'borlaof']
['hdllo', 'hello', 'hfllo']

Now I don’t know how question bans work, but I hope you use your “time-out” to study this code a little bit and then make the appropriate changes to the one above.

Note that this is Python 3.3+, if it matters.

Hope this helps!

2

solved solution to this recursive function questions? [closed]