CS61A 系列课程笔记(一)

xiaoxiao2021-02-28  15

嗯 今天刚看第二周的课程,大量的 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

注意: 在函数中编写测试信息的时候>>>后面需要有一个空格,否则就会报错!! 熟悉下吧,就是不知道在实际中应该怎么应用

转载请注明原文地址: https://www.6miu.com/read-2800293.html

最新回复(0)