How to think like a Computer Scientist: 课后习题第六章 13-19

#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      penglaixy
#
# Created:     27/07/2013
# Copyright:   (c) penglaixy 2013
# Licence:     <your licence>
#-------------------------------------------------------------------------------
import sys

def test(did_pass):
    '''
    print the result of a test
    '''
    linenum = sys._getframe(1).f_lineno
    if did_pass:
        msg = 'Test at line {0} ok'.format(linenum)
    else:
        msg = 'Test at line {0} failed'.format(linenum)
    print msg

def slope(x1,y1,x2,y2):
    '''
    y=kx + b ,there we caculate the k
    '''
    return (float(y1-y2))/(float(x1-x2))

def intercept(x1,y1,x2,y2):
    '''
    y=kx + b ,there we caculate the b
    '''
    return y1-slope(x1,y1,x2,y2)*x1

def is_even(num):
    return num % 2 == 0

def is_odd(num):
    return not is_even(num)

def is_factor(f, n):
    return n >= f and n%f == 0

def is_mutiple(n,f):
    return n > f and is_factor(f,n)

def f2c(t):
    '''
    c = (f - 32)*5/9
    '''
    t = float(t)
    return round((t-32)*5/9)

def c2f(t):
    '''
    f = c*9/5 + 32
    '''
    t = float(t)
    return round(t*9/5+32)

def test_suite():
    '''
    Run the suite of tests for code in this module
    '''
    test(slope(5,3,4,2)==1.0)
    test(slope(1,2,3,2)==0.0)
    test(slope(1,2,3,3)==0.5)
    test(slope(2,4,1,2)==2.0)
    test(intercept(1,6,3,12) == 3.0)
    test(intercept(6,1,1,6) == 7.0)
    test(intercept(4,6,12,8) == 5.0)

    test(is_even(12) == True)
    test(is_even(13) == False)

    test(is_odd(12) == False)
    test(is_odd(13) == True)

    test(is_factor(3,12))
    test(is_factor(7,14))
    test(is_factor(15,15))
    test(is_factor(1,15))
    test(not is_factor(25,15))
    test(not is_factor(5,12))
    test(not is_factor(7,15))

    test(is_mutiple(12,3))
    test(is_mutiple(12,4))
    test(is_mutiple(12,6))
    test(not is_mutiple(12,7))
    test(not is_mutiple(12,5))
    test(not is_mutiple(12,12))

    test(f2c(212) == 100)
    test(f2c(32) == 0)
    test(f2c(-40)== -40)
    test(f2c(36) == 2)
    test(f2c(37) == 3)
    test(f2c(38) == 3)
    test(f2c(39) == 4)

    test(c2f(0) == 32)
    test(c2f(100) == 212)
    test(c2f(-40) == -40)
    test(c2f(12) == 54)
    test(c2f(18) == 64)
    test(c2f(-48) == -54)


def main():
    test_suite()

if __name__ == '__main__':
    main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值