the lecture 6

1.how python works

python don't check the type of the argument you take in so be careful with the name of the function and make sure the way you name the name can make you understand what is going on with the function. and what's more make sure you know the what kinds of diagram you should pass to a function! and what type of value the function will return!!be careful,i had made the mistakes for many times and spend a lot of my time to debug!

2.recursion 递归

1.为base case——递归最底层的情况 为他设置出口conditional statement

2.recursion case——递归部分 为他调用递归函数进行递归,而base case基础实例就不进行递归操作

3.return 递归函数必须要return

def split(digits):
    return digits // 10, digits % 10 

def add_digits(all_but_last):
    if all_but_last < 10:
        return all_but_last
    else:
        all_but_last,last = split(all_but_last)
        return add_digits(all_but_last) + last

2.1 frames diagram of recursion

和普通的其他的frame一样,只不过是对某个function的反复调用,然后依次return,更形象的说法是递归。

2.2 the recursion leap of faith

what is the faith of recursion? it is that there is no need for you to think about exactly what happened in the recursion call function because it will be entire and make you loose your mind,the only thing you need to do is that just believing the recursion function will solve the simpler question for you.

it won't be a good idea to have assignment statement in recursion function just because the new called recursion function will surely loose the old data. a good method to solve the problem is turn to operator the operands when you return the recursion function here is a fake code to show

def a_bad_recursion(n)
    count = 0
    <condition>
    return a_bad_recursion(n)

there a also a basic structure tree main parts condition, basic base, recursion case.

def recursion()
    if condition:
        basic base
    else:
        recursion base

1.注意base case 的出口条件

2.递归函数是否预期传递(不必细想细节)just past in

3.是否有return

3. mutual recursion

两个递归函数相互引用,这里是以银行卡的奇位校验为例

def split(n):
    return n // 10 , n % 10

def luhn_sum(n):
    if n < 10:
        return n
    else:
        all_but_last, last = split(n)
        return luhn_double_sum(all_but_last) + last

def luhn_double_sum(n):
    all_but_last, last = split(n)
    luhn_digits = add_digits(last*2)
    if n < 10:
        return luhn_digits
    else:
        return luhn_sum(all_but_last) + luhn_digits

这里都是function内先切下一位数last,然后互相return以达到错位校验的目的。

需要注意的是第一次return luhn_double_sum function时对n的conditional statement

先call split() function 把last拿到然后调用add_digits() 否则会把整个n变成一位数.

lab 2

how to draw picture of frames

  • frames object
  • 3 steps
  • one lambda or function can choose not writing target number of the frames name

how to name the diagram

  • show what the diagram is going to do
  • special use like i j k for count ,x y z for natural number. f g for function name