我正在使用递归函数,需要在函数内打印一次

时间:2014-11-23 19:02:36

标签: python python-3.x recursion printf

我正在使用python 3并且需要在函数内打印最终结果(这不是可选的)。相反,它每次通过功能时都会打印。

def reverseDisplay(number):
#base case 
#if number is only one digit, return number

  if number<10:
        return number 
  else:
        result = int(str(number%10) + str(reverseDisplay(number//10)))


  print(result)
  return(result)

def main():
     number = int(input("Enter a number: "))
     reverseDisplay(number)

main()

如果您输入12345,则会打印出

21

321

4321

54321

我希望它打印出54321

4 个答案:

答案 0 :(得分:1)

您只需将print声明移出reverseDisplay并转入main

def reverseDisplay(number):
#base case 
#if number is only one digit, return number

  if number<10:
        return number 
  else:
        result = int(str(number%10) + str(reverseDisplay(number//10)))
  return result

def main():
    number = 12345
    print reverseDisplay(number)

main()

答案 1 :(得分:1)

如果你真的需要在递归函数中打印它,你必须添加一个参数(在这个例子中称为first),以确保你只在第一次打印:

def reverseDisplay(number, first=True):
    if number<10:
        return number 
    else:
        result = int(str(number%10) + str(reverseDisplay(number//10, False)))
        if first:
            print(result)
        return result

答案 2 :(得分:1)

以下对我有用(在我发现在线Python 3翻译后):

def reverseDisplay(n):
    tmp = n % 10       # Determine the rightmost digit,
    print(tmp, end="") #  and print it with no space or newline.
    if n == tmp:       # If the current n and the rightmost digit are the same...
        print()        #    we can finally print the newline and stop recursing.
    else:              # Otherwise...
        reverseDisplay(n // 10)  # lop off the rightmost digit and recurse.

如果除了打印之外还需要返回反转值:

def reverseDisplay(n):
    tmp = n % 10
    print(tmp, end="")
    if n == tmp:
        print()
        return tmp
    else:
        return int(str(tmp) + str(reverseDisplay(n // 10)))

答案 3 :(得分:0)

试试这个:

def reverseDisplayPrinter(number):
    print reverseDisplay(number)

def reverseDisplay(number):
    if number<10:
        return number 
    else:
        result = int(str(number%10) + str(reverseDisplay(number//10)))

    return(result)

def main():
    number = int(input("Enter a number: "))
    reverseDisplayPrinter(number)

main()