• 小甲鱼Python第023、024讲递归:这帮小兔崽子、汉诺塔 | 课后测试题及参考答案


    斐波那契函数

    1、迭代

    def fab_1(n):
        result1 = 1
        result2 = 1
        m=1
        if n<1:
            print("错误")
        while m <= n :
            if m < 3:
                result1
                m+=1
            elif m >= 3 :
                result = result1+result2
                result1=result2
                result2=result
                m+=1
        return result
    g=fab_1(12)
    print(g)

    2、递归

     1 def fab_2(n):
     2     result1=1
     3     result2=1
     4     if n<1:
     5         print("cuowu")
     6     while n>=1:
     7         if n < 3:
     8             return result1
     9             n-=1
    10         else:
    11             return fab_2(n-1)+fab_2(n-2)
    12             n-=1
    13 
    14 print(fab_2(12))

    0.使用递归编写一个十进制转换为二进制的函数(要求采用“取2取余”的方式,结果与调用bin()一样返回字符串形式)。

    1 def fun(n):
    2     result = ""
    3     if n>=2:
    4         a = n%2
    5         return fun(n//2)+str(a)
    6     else:
    7         return result+str(n)
    8 print(fun(10))

    1.写一个函数get_digits(n),将参数n分解出每个位的数字并按顺序存放到列表中,举例:get_digits(12345)==>[1,2,3,4,5]

    1 result=[]
    2 def get_digits(n):
    3     if n>0 :
    4         result.insert(0,n % 10)
    5         get_digits(n // 10)
    6     elif n<0:
    7         print("数字不符合")
    8     return result
    9 print(get_digits(12345))

    2.还记得求回文字符那道题吗?现在让你使用递归的方式来求解,还能傲娇的说我可以吗?

     1 def huiwenfu(n):
     2     list1 = list(n)
     3     i=0
     4     result = 1
     5     length = len(list1)
     6     while length >0 and i <= (length//2):
     7         if list1[0+i] == list1[-1-i]:
     8             i += 1
     9         else:
    10             result = 0
    11             break
    12     if result:
    13         print("是回文符")
    14     else:
    15         print("不是回文符")
    16 n=input("请输入一串文字:")
    17 huiwenfu(n)

    3.使用递归编程求解以下问题:

     1  #方法一:
     2 def years_old(a):
     3     n = 2
     4     i = 5
     5     #5个人 第一人已知年龄,再额外加4次即可
     6     while i > 1:
     7         a = a + n
     8         i -= 1
     9     return a
    10 print(years_old(10))
    11 # 方法二
    12 def years_old1(n):
    13     if n == 1:
    14         return 10
    15     else:
    16         return years_old1(n-1) + 2
    17 print(years_old1(5))
  • 相关阅读:
    分治法求最大子序列
    6.2 链表 (UVa 11988, 12657)
    6.1 栈和队列 (UVa 210, 514, 442)
    S-Tree (UVa 712) 二叉树
    Equilibrium Mobile (UVa 12166) dfs二叉树
    Patrol Robot (UVa 1600) BFS
    Knight Moves (UVa 439) BFS
    Tree Recovery (UVa 536) 递归遍历二叉树
    Parentheses Balance (Uva 673) 栈
    Self-Assembly (UVa 1572)
  • 原文地址:https://www.cnblogs.com/IT-NXXB/p/13049127.html
Copyright © 2020-2023  润新知