这个递归函数问题的解决方案?

时间:2014-10-18 15:52:04

标签: python function recursion

有人能解决这个递归函数问题吗?

  

编写一个程序,确定电话号码的所有字母翻译。如果输入字符串中出现不可翻译的字符,则应将其作为常量传递。   输入:7位数字串的序列,每行一个。由一串7 0&#39>终止。

     

示例输入:

borla63
0000000
     

示例输出:

borlamd,borlame,borlamf,borland,borlane,borlanf,borlaod,borlaoe,borlaof
    #data5.py
import string
lets=["","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]
def rep(numb,index):
    if index<len(numb) and (numb[index]) not in assi at +"01"
    for letter in lets[int(numb[index])]:
        rep(numb[:index] +letter+numb[index+1:],index+1)
    elif index>= len(numb:
        print(numb)
    else:
        rep(numb,index+1)
while True:
        number=input()
        if number=="0000000":
                     break
                     rep(number,0)

1 个答案:

答案 0 :(得分:0)

我理解下选票和结束票,因为你在这里没有表现出丝毫的努力。另一方面,这是一个非平凡的问题。我会假设你真的对这个问题的解决方案感兴趣,我会告诉你我将如何写这个(没有看过你发布的代码)。

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)))

产生

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

现在我不知道问题禁令是如何工作的,但我希望你用“超时”来研究这段代码,然后对上面的代码进行适当的修改。

请注意,如果重要的话,这是Python 3.3+。

希望这有帮助!

相关问题