Python 递归 Resursion()

时间:2023-04-11 08:45:26

条件:

  ①递归有最小值或有确定值

  ②fun(x) = ax * bfun(x-1) 类似规则

eg.   n! :

  ①1! = 1

  ②n! = n* (n-1)!

  def factorial (n):

    if n==1: return 1

    else:return n*factorial(n-1)

eg.    x^n :

  ① n = 0 x^n = 1

  ②x^n = x*x^(n-1)

  def power(x,n):

    if n == 0: return 1

    else: return x*power(x,n-1)

funcation eg. Armstrong Number: len(str(number)) = n     str(number)[0]^n+str(number)[1]^n+str(number)[2]^n........ = number         eg. 153 = 1^3+5^3+3^3

number = input('Enter your tested number: ')
temp = 0
digit=len(str(number))
power=digit
while digit>0:
    temp += (int(str(number)[digit-1]))**power
    print (temp)
    digit -= 1
if temp == number: print ('yes',number,'is an Armstrong Number')
if temp != number: print ('no',number,'is not an Armstrong Number')