#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: penglaixy
#
# Created: 27/07/2013
# Copyright: (c) penglaixy 2013
# Licence: <your licence>
#-------------------------------------------------------------------------------
import sys
import random
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 num_digits(n):
count = 0
n = abs(n)
while True:
count += 1
n = n//10
if n == 0:
break
return count
def num_even_digits(n):
count = 0
while True:
if n % 2 == 0:
count += 1
n = n//10
if n == 0:
break
return count
def sum_of_squares(xs):
total = 0
for i in xs:
total += i**2
return total
def test_suite():
'''
Run the suite of tests for code in this module
'''
test(num_digits(0) == 1)
test(num_digits(-12345) == 5)
test(num_even_digits(123456) == 3)
test(num_even_digits(2468) == 4)
test(num_even_digits(1357) == 0)
test(num_even_digits(0) == 1)
test(sum_of_squares([2,3,4]) == 29)
test(sum_of_squares([]) == 0)
test(sum_of_squares([2,-3,4]) == 29)
def play_once(human_plays_first):
'''
if the parameter is True,the human play first,else the computer play first.
when the round ends, the result value of the funciton is one of
-1 human wins, 0 game drawn, 1 computer wins
'''
rng = random.Random()
#pick a random result between -1 and 1
result = rng.randrange(-1,2)
print ("Human plays first = {0}, winner = \
{1}".format(human_plays_first, result))
return result
def human_interaction():
human_score = 0
computer_score = 0
drawn_score = 0
pre_first = True
total_rounds = 0
while True:
total_rounds += 1
result = play_once(pre_first)
if result == -1:
human_score += 1
print "I win!"
elif result == 0:
computer_score += 1
print "You win!"
else:
drawn_score += 1
print "Game drawn!"
print "human score: {0}\ncomputer score:{1}\ngame drawn:{2}".format(
human_score, computer_score, drawn_score)
print "Human wins percent : {0}%".format(human_score*100/total_rounds)
command = raw_input("Do you want to play again?[y/n]")
if command[0] == 'y':
print "Play again"
else:
break
if pre_first == True:
pre_first = False
else:
pre_first = True
print "Goodbye!"
return
def main():
test_suite()
human_interaction()
if __name__ == '__main__':
main()
How to think like a Computer Scientist: 课后习题第七章 14-17
最新推荐文章于 2013-09-19 08:45:00 发布