计算机科学和python编程导论 week three classcode & classwork

ClassCode

  • 递归

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20

    # coding: utf-8
    # author: nemo_chen
    # 递归
    def (a, b):
    result = 0
    while b > 0:
    result += a
    b -= 1
    return result
    def recurMul(a, b):
    if b == 1:
    return a
    else:
    return a + recurMul(a, b-1)
    def factR(n):
    if n == 1:
    return n
    else:
    return n * factR(n-1)
  • 汉塔塔

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    #!/usr/bin/env python
    # coding: utf-8
    # author: nemo_chen
    def printMove(fr, to):
    print('Move from ' + str(fr) + ' to ' + str(to))
    def Towers(n ,fr, to, spare):
    if n == 1:
    printMove(fr, to)
    else:
    Towers(n-1, fr, spare, to)
    Towers(n, fr, to, spare)
    Towers(n-1, spare, to, fr)
  • 斐波那契

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #!/usr/bin/env python
    # coding: utf-8
    # author: nemo_chen
    def fib(x):
    assert type(x) == int and x >= 0
    if x == 0 or x == 1:
    return 1
    else:
    return fib(x-1) + fib(x-2)