【问题标题】:solution to this recursive function questions? [closed]这个递归函数问题的解决方案? [关闭]
【发布时间】:2014-12-14 00:25:06
【问题描述】:

谁能解决这个递归函数问题?

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

示例输入:

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)

【问题讨论】:

  • 欢迎来到 Stack Overflow!看起来您希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的编码人员编写代码,但他们通常只有在发布者已经尝试自己解决问题时才会提供帮助。展示这项工作的一个好方法是包含您迄今为止编写的代码、示例输入(如果有的话)、预期输出和您实际获得的输出(控制台输出、堆栈跟踪、编译器错误 - 不管是什么适用的)。您提供的详细信息越多,您可能收到的答案就越多。
  • 这个问题来自之前的比赛,我复制了一部分解决方案,但我错误地复制了一部分,并设法破解了代码。社区愿意为我修复此代码吗?注意它不会产生输出。
  • 我们对学生没有问题,但这不是一个主题问题;请花点时间阅读帮助中心的资料:stackoverflow.com/help/asking
  • 别再那么挑剔了,下次只是帮助别人而不是抨击他们!
  • 没有。没有人“抨击”或“欺负”你,礼貌地要求你表现出一些努力。本网站对什么构成可接受的问题有明确的标准,并且不是代码编写服务;如果您对此有疑问,请查找其他网站。

标签: python function recursion


【解决方案1】:

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

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+,如果重要的话。

希望这会有所帮助!

【讨论】:

  • 非常感谢!我只是在星期四的 comp sci 团队选拔测试中有点压力,所以你的回答对我有很大帮助!
  • @Lilyk27 没问题。我相信你稍后会带着准备好的问题回到 SO ;-) 祝你考试顺利!
猜你喜欢
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-09
  • 2021-01-17
  • 1970-01-01
  • 2011-07-20
  • 2020-03-26
相关资源
最近更新 更多