#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: penglaixy
#
# Created: 11/08/2013
# Copyright: (c) penglaixy 2013
# Licence: <your licence>
#-------------------------------------------------------------------------------
import sys
import random
import string
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 add_vectors(u, v):
new_list=[]
if len(u) != len(v):
print "Parameter error!"
for i in range(len(u)):
new_list.append(u[i]+v[i])
return new_list
def scalar_mult(s, v):
new_list = []
for item in v:
new_list.append(s*item)
return new_list
def dot_product(u, v):
total = 0
if len(u) != len(v):
print "Parameter error!"
for i in range(len(u)):
total += u[i]*v[i]
return total
def cross_product(u, v):
'''
a×b=(aybz-azby)i+(azbx-axbz)j+(axby-aybx)k
'''
new_list = []
if len(u) != 3 or len(v) != 3:
print "Parameter error!"
new_list.append(u[1]*v[2] - u[2]*v[1])
new_list.append(u[2]*v[0] - u[0]*v[2])
new_list.append(u[0]*v[1] - u[1]*v[0])
return new_list
def replace_str(str, old, new):
while True:
index = str.find(old)
if -1 != index:
str = str[:index] + new + str[(index + len(old)):]
else:
break
return str
def replace(s, old, new):
list_str = s.split()
new_list = []
for str in list_str:
new_list.append(replace_str(str,old, new))
return " ".join(new_list)
pass
def swap(x,y):
print("before swap statement: x:", x, "y:", y)
(x,y) = (y,x)
x[1] = "hello"
y[1] = "world"
print("after swap statement: x:", x, "y:", y)
def test_suite():
'''''
Run the suite of tests for code in this module
'''
test(add_vectors([1,1], [1,1]) == [2,2])
test(add_vectors([1,2], [1,4]) == [2,6])
test(add_vectors([1,2,1], [1,4,3]) == [2,6,4])
test(scalar_mult(5, [1,2]) == [5, 10])
test(scalar_mult(3, [1,0,-1]) == [3, 0, -3])
test(scalar_mult(7, [3, 0, 5, 11, 2]) == [21, 0, 35, 77, 14])
test(dot_product([1,1],[1,1]) == 2)
test(dot_product([1, 2],[1,4]) == 9)
test(dot_product([1,2,1],[1,4,3]) == 12)
test(cross_product([1,2,3],[4,5,6]) == [-3, 6, -3])
test(cross_product([2,3,4],[2,3,4]) == [0,0,0])
test(replace("Mississippi",'i','II') == 'MIIssIIssIIppII')
s = "I love spom! Spom is my favorite food. Spom, spom, yum!"
test(replace(s,'om','am') == "I love spam! Spam is my favorite food. Spam, spam, yum!")
test(replace(s,'o', 'a') == "I lave spam! Spam is my favarite faad. Spam, spam, yum!")
pass
def main():
test_suite()
a = ["This", "is", "fun"]
b = [2,3,4]
print("before swap statement: a:", a, "b:", b)
swap(a,b)
print("after swap statement: a:", a, "b:", b)
if __name__ == '__main__':
main()
How to think like a Computer Scientist: 课后习题第十一章 5-11
最新推荐文章于 2013-09-18 19:54:43 发布