#-------------------------------------------------------------------------------
# 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 count_odd(list_num):
count = 0
for i in list_num:
if i % 2 == 1:
count += 1
return count
def sum_even(list_num):
total = 0
for i in list_num:
if i % 2 == 0:
total += i
return total
def sum_neg(list_num):
total = 0
for i in list_num:
if i < 0:
total += i
return total
def sum_word5(list_word):
count = 0
for i in list_word:
if len(i) == 5:
count += 1
return count
def sum_until_even(list_num):
total = 0
for i in list_num:
if i % 2 == 0:
break
else:
total += i
return total
def count_befor_sam(list_word):
count = 0
for i in list_word:
count += 1
if i == 'sam':
break
return count
def caculate_square_root(n):
'''
better = (approx + n/approx)/2
'''
approx = n/2.0
while True:
better = (approx + n/approx)/2.0
print 'This time better is ', better
if abs(better - approx) < 0.001:
break
approx = better
return better
def is_prime(n):
for i in range(2, n//2 + 1):
if n % i == 0:
return False
return True
def print_triangular_numbers(n):
total = 0
for i in range(1,n+1):
total += i
print n, '\t', total
def test_suite():
'''
Run the suite of tests for code in this module
'''
test(count_odd([1,2,3,4,5,6,7]) == 4)
test(count_odd([2,4,6,8,10]) == 0)
test(sum_even([1,2,3,4,5,6,7]) == 12)
test(sum_even([1,3,5,7]) == 0)
test(sum_neg([-2,-4,-5,-6]) == -17)
test(sum_neg([1,2,3,4,5]) == 0)
test(sum_word5(['list','word','world','apple']) == 2)
test(sum_word5(['no','yes','live','home']) == 0)
test(sum_until_even([2,3,4,5,6,7]) == 0)
test(sum_until_even([1,3,5,7,9,11]) == 36)
test(count_befor_sam(['sam','he','she']) == 1)
test(count_befor_sam(['he','sam','she']) == 2)
test(count_befor_sam(['he','she','they']) == 3)
caculate_square_root(25)
print_triangular_numbers(1)
print_triangular_numbers(2)
print_triangular_numbers(3)
print_triangular_numbers(4)
print_triangular_numbers(5)
test(is_prime(2))
test(is_prime(3))
test(is_prime(11))
test(not is_prime(35))
test(is_prime(19911121))
def main():
test_suite()
if __name__ == '__main__':
main()
How to think like a Computer Scientist: 课后习题第七章 1-10
最新推荐文章于 2013-09-19 14:31:59 发布