CS61A 系列課程筆記(一)

嗯 今天剛看第二週的課程,大量的 reading 材料我是真的要崩潰了,全英。。。。
我覺得我小學的時候英語挺好的呀,都被老師表揚過呢,滑稽.jpg (逃

每週的reading 是真的很多啊,不說了 我廢話好多啊

**********************正文***********************
看到函數一節,reading 1.5材料中 介紹了對函數的測試 主要講了三種:
1. assert 不太常用
以斐波那契數列爲例下一個函數

>>> def fib(n): # n>2
...     a,b=0,1
...     for i in range(2,n+1):
...         a,b=b,a+b
...     return b
...
>>> fib(4)
3
>>> fib(5)
5
>>> fib(6)
8
>>> assert fib(6)==8,'the sixth number should be 8,whis content will be returned
 when error'
>>> assert fib(6)==7,'this is not right i just try to see what will happen when
error'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: this is not right i just try to see what will happen when error
>>>


2.第二種是在函數中寫入一些信息,當我們調用doctest的testmod方法時就會返回

>>> def sum_num(n):
...     """this code is to cal the sum of the n numbers
...     >>> sum_num(10)
...     55
...     >>> sum_num(100)
...     5050
...     """
...     total,k=0,1
...     for i in range(n):
...         total,k=total+k,k+1
...     return total
...
>>> from doctest import testmod
>>> testmod()
TestResults(failed=0, attempted=2)


3.第三種也是導入doctest模塊的一個函數,該函數爲run_docstrig_examples
這個函數在調用的時候需要傳入參數,第一個參數是被測試的函數名,第二個參數是globals() 這是固定的,第三個參數是True表示把具體的信息都展示出來

>>> def sum(x,y):
...     """this function is to cal the sum of two given numbers
...     >>> sum(1,2)
...     3
...     >>> sum(3,4)
...     7
...     """
...     return x+y
...
>>> from doctest import run_docstring_examples
>>> run_docstring_examples(sum,globals(),True)
Finding tests in NoName
Trying:
    sum(1,2)
Expecting:
    3
ok
Trying:
    sum(3,4)
Expecting:
    7
ok

3.又自己寫了一個函數,帶有測試的哦

# -*- coding: utf-8 -*-
"""
Created on Sun May  6 20:41:21 2018

@author: Administrator
"""

def sum_num_xuanxuan(n,times):
    """this function is to cal two sub_function with different features----xuanxan

    >>> sum_num_xuanxuan(5,3)
    225
    >>> sum_num_xuanxuan(5,1)
    15
    """
    total,k=0,1
    while k<=n:
        total,k=total+pow(k,times),k+1
    return total

下面是在console平臺寫的測試:

from doctest import testmod

testmod()
Out[3]: TestResults(failed=0, attempted=2)

from doctest import run_docstring_examples

run_docstring_examples(sum_num_xuanxuan,globals(),True)
Finding tests in NoName
Trying:
    sum_num_xuanxuan(5,3)
Expecting:
    225
ok
Trying:
    sum_num_xuanxuan(5,1)
Expecting:
    15
ok

注意:
在函數中編寫測試信息的時候>>>後面需要有一個空格,否則就會報錯!!
熟悉下吧,就是不知道在實際中應該怎麼應用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章