ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

CS61A 18sp -- Lecture8(Tree Recursion) 笔记

2020-11-23 16:59:10  阅读:338  来源: 互联网

标签:count 10 18sp return -- Recursion cascade print partitions


Lecture8 Tree Recursion

Reading 1.7
1. Order of Recursive Calls
<1>【eg1】The Cascade Function

>>> def cascade(n):
        """Print a cascade of prefixes of n."""
        if n < 10:
            print(n)
        else:
            print(n)
            cascade(n//10)
            print(n)
            
>>> cascade(2013)
2013
201
20
2
20
201
2013

<2>【eg2】Inverse Cascade

def inverse_cascade(n): grow(n)
    print(n)
    shrink(n)
def f_then_g(f, g, n):
	 if n:
		f(n)
		g(n)
		
grow = lambda n: f_then_g(grow, print, n//10) shrink = lambda n: f_then_g(print, shrink, n//10)


>>> inverse_cascade(2013)
1
12
123
1234
123
12
1

2. Tree Recursion
<1>【eg1】Fibonacci numbers(与树结构进行联系)

n: 0, 1, 2, 3, 4, 5, 6, 7, 8, …,
fib(n): 0, 1, 1, 2, 3, 5, 8, 13, 21,

	def fib(n):
	    if n == 1:
	        return 0
	    if n == 2:
	        return 1
	    else:
	        return fib(n-2) + fib(n-1)
	
	result = fib(6)

<2>与树结构的联系在这里插入图片描述

  1. Repetition in Tree-Recursive Computation
  2. 【举例】Counting Partitions

The number of partitions of a positive integer n, using parts up to size m, is the number of ways in which n can be expressed as the sum of positive integer parts up to m in increasing order.
count_partitions(6, 4)
6 = 2 + 4
6 = 1 + 1 + 4
6 = 3 + 3
6 = 1 + 2 + 3
6 = 1 + 1 + 1 + 3
6 = 2 + 2 + 2
6 = 1 + 1 + 2 + 2
6 = 1 + 1 + 1 + 1 + 2
6 = 1 + 1 + 1 + 1 + 1 + 1

解题思路
• Recursive decomposition: finding simpler instances of the problem.
• Explore two possibilities: •Use at least one 4
•Don’t use any 4
• Solve two simpler problems: •count_partitions(2, 4) •count_partitions(6, 3)
• Tree recursion often involves exploring different choices.
在这里插入图片描述

所用代码如下:

>>> def count_partitions(n, m):
        """Count the ways to partition n using parts up to m."""
        if n == 0:
            return 1
        elif n < 0:
            return 0
        elif m == 0:
            return 0
        else:
            return count_partitions(n-m, m) + count_partitions(n, m-1)

>>> count_partitions(6, 4)
9
>>> count_partitions(5, 5)
7
>>> count_partitions(10, 10)
42

标签:count,10,18sp,return,--,Recursion,cascade,print,partitions
来源: https://blog.csdn.net/weixin_45461952/article/details/110000522

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有