python 核心编程课后练习(chapter 6)

时间:2023-12-14 13:47:50

6-1

 #6-1

 #help(string)
import string str = "helloworld"
substr = "h1e" if string.find(str, substr) != -1:
print"substr=%s is part of %s" % (substr, str)
else:
print"not substring"

6-2

 #6-2
import string
import keyword alphas = string.letters + '_'
nums = string.digits print "welcome"
print "testees must be at least 2 chars long." ips = raw_input("identifier:") if len(ips)== 1:
if ips[0] not in alphas:
print"single letter invalid"
else:
if not keyword.iskeyword(ips):
print "valid"
else:
print "invalid is keyword"
#print "valid"
elif len(ips) > 1:
if ips[0] not in alphas:
print "first symbol invalid"
else:
for others in ips[1:]:
if others not in alphas + nums:
print "invalid remaining"
break
else:
if not keyword.iskeyword(ips):
print "valid"
else:
print "invalid, is keyword"
else:
print"string should be at least 2 chars"

6-3

 #6-3   

 import string

 nums = string.digits

 str=raw_input("Enter the nums:")
#a
a = []
for e in str:
a.append(int(e))
a.sort(reverse = True)
print a
#b
b = sorted(str, reverse = True)
print b

6-4

 #6-4

 def average(a):
size = len(a)
sum = 0
for e in a:
sum += int(e)
return float(sum)/float(size) print """
(a)add new
(other)exit
"""
a = [] opt = raw_input("your opt:")
while opt == "a":
a.append(raw_input("Enter the score:"))
opt = raw_input("your opt:") print "the average of the scores:%f" % average(a)

6-5

 #6-5(a)

 inputstring = raw_input("Enter the string:")

 sz = len(inputstring)

 if sz == 1:
print inputstring
else:
i = 0
while i<sz:
if (i-1)<0:
print inputstring[i], inputstring[i+1]
elif (i+1)>=sz:
print inputstring[i-1], inputstring[i]
else:
print inputstring[i-1], inputstring[i], inputstring[i+1] i = i+1
 #6-5(b)

 def str_cmp_helper(str1, str2):
lens = len(str1)
i = 0
while i<lens:
if str1[i]>str2[i]:
return 1
elif str1[i]<str2[i]:
return -1
i = i+1
return 0 def str_cmp(str1, str2):
if len(str1)>len(str2):
return 1
elif len(str1)<len(str2):
return -1
else:
return str_cmp_helper(str1, str2) str1 = raw_input("enter the str1:")
str2 = raw_input("enter the str2:") result = str_cmp(str1, str2)
if result == 1:
print "str1:%s > str2:%s" % (str1, str2)
elif result == 0:
print "str1:%s is the same to str2:%s" % (str1, str2)
else:
print "str1:%s < str2:%s" % (str1, str2)
 #6-5(c)

 def is_palin(str):
lens = len(str) if lens == 1:
return True
else:
i = 0
while i<lens/2:
if str[i] <> str[lens -1 - i]:
return False
else:
i= i+1
return True inputstring = raw_input("enter the string:") if is_palin(inputstring):
print "%s is palin"% inputstring
else:
print "%s is not palin"% inputstring
 #6-5(d)

 def palin(str):
lens = len(str)
if lens%2 != 0:
i = lens -1 -1
else:
i = lens - 1 while i>=0:
str = str +str[i]
i= i-1 return str inputstring = raw_input("enter the string:") print"the palin of %s is: %s" % (inputstring, palin(inputstring))

6-6

 #6-6

 def trim_end_blacks(str):
lens = len(str)
i = lens -1
#trim the end blanks
while i >=0 and str[i] == ' ':
str = str[:i]
i = i- 1
#trim the start blanks
while str[0]==' ' and len(str)!=0:
str = str[1:]
print str inputstr = raw_input("enter the string:") print """after trim the blanks in start and end pos:
%s change to %s
"""%(inputstr, trim_end_blacks(inputstr))

6-8

 #6-8

 print """
(zero,one, two, three, four, five, six, seven, eight, nine,),
(ten,eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen,),
(twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety,)
(hundred, thousand, million, billion,...)
""" units = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
tens = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
hundreds = ["hundred", "thousand", "million", "billion"] def num_to_eng(num):
#get thousand
need_and = False
eng_str = ""
if(num == 0):
eng_str = "Zero"
return eng_str
num = num%10000
if num/1000 != 0:
need_and = True
eng_str = eng_str + units[num/1000-1]+" thousand "
num = num%1000
if num/100 !=0:
need_and = True
eng_str = eng_str + units[num/100 - 1]+" hundred "
if(need_and):
eng_str = eng_str + "and " num = num%100
if(num>19):
eng_str = eng_str + tens[num/10 - 2]+" "
num = num%10
if(num != 0):
eng_str = eng_str + units[num-1]
elif(num>9):
eng_str = eng_str + teens[num -10]
else:
eng_str = eng_str+ units[num-1]
return eng_str
num = raw_input("enter the number:")
print num_to_eng(int(num))

6-9

 #6-9

 def min_to_hm(t):
h = t/60
h=h%24 m = t%60 return "%d:%d"%(h,m) t = raw_input("enter the mins:")
print "the time is:%s" % min_to_hm(int(t))

6-10

 #6-10
import string
def ul_covert(str):
return string.swapcase(str) str = raw_input("enter the string:") print ul_covert(str)

6-11

 #6-11
def n_to_ip(num):
str = "%d" % num
if len(str)!= 12:
print "invalid ip"
return ""
else:
return str[:3]+":"+str[3:6]+":"+str[6:9]+":"+str[9:12] def ip_to_n(str):
if len(str)!=15:
print "invalid ip str"
return 0
else:
return int(str[0:3]+str[4:7]+str[8:11]+str[12:15]) num = int(raw_input("enter the ip num:"))
print"after covert to ip string: %s" % n_to_ip(num)
print"after convert to ip num: %d" % ip_to_n(n_to_ip(num))

6-12

 #6-12

 def findchr(string, char):
if char == "":
return 0
lens = len(string)
if lens == 0:
return -1
i=0
while i<lens:
if string[i] == char:
return i
else:
i=i+1
return -1 def rfindchr(string, char):
lens = len(string)
if char == "":
return lens
if lens == 0:
return -1
i = lens -1
while i>=0:
if string[i] == char:
return i
else:
i=i-1 return -1 def subchr(string, origchar, newchar):
lens = len(string)
i = 0
while i<lens:
if string[i]==origchar:
string = string[0:i]+newchar+string[i+1:]
i= i+1
return string print findchr("","")
print findchr("", "a")
print findchr("abc","a")
print findchr("abc", "d") print rfindchr("","")
print rfindchr("", "a")
print rfindchr("abc","a")
print rfindchr("dabcd", "d") print subchr("test", "t", "a")

6-13

 #6-13
#import string def atoc(str):
real = 0
img = 0 lens = len(str) i = lens -1
if str[i] == "j":
if str[i-1]==")":
j = i -2
while j>=0:
if str[j] != "(":
j= j-1
else:
break
img = float(str[j+1:i-1])
i = j-1
else:
j=i
while j>0:
if str[j]=="+" or str[j]=="-":
break
else:
j=j-1
img = float(str[j+1:i])
i=j
real = float(str[0:i])
return complex(real, img) str = raw_input("enter the complex:")
print atoc(str)

6-14

 #6-14
import string
import random def Rockhambocu(pc_opt,y_opt):
"""
pc_opt, the option of pc
y_opt, your option
(r)rock
(s)scissor
(c)cloth
"""
str_opt = "rsc" rsc_rule =[[0,-1,1],[1,0,-1],[-1,1,0]] pc_i = string.find(str_opt, pc_opt)
y_i = string.find(str_opt, y_opt) return rsc_rule[pc_i][y_i] def RSC_result(r):
result = ["fail", "draw", "win"]
return result[r+1] print """
enter your option:
(r)rock
(s)scissor
(c)cloth
(other)default r
""" y_opt = raw_input() str_opt ="rsc"
pc_opt = str_opt[random.randint(0,2)]
print "PC option is %s" % pc_opt print "you %s"% RSC_result(Rockhambocu(pc_opt, y_opt))

6-15

 #6-15

 def is_leap(y):
if y/400 == 0:
return True
elif y/4 == 0 and y/100 != 0:
return True
return False def check_date_valid(y, m, d):
"""
-1, invalid date
1, valid date
"""
if y<1:
return -1
if m<1 or m>12:
return -1
month_days = [31,28, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30]
if is_leap(y):
month_days[1] = 29
if d<1 or d>month_days[m-1]:
return -1 return 1 def calcu_days(y, m, d):
sum = d
month_days = [31,28, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30]
year_days = 365 if is_leap(y):
month_days[1] = 29 i = 1
while i<m:
sum = sum + month_days[i-1]
i=i+1
i=1
while i<y:
if is_leap(i):
sum = sum + year_days + 1
else:
sum = sum + year_days
i = i +1
return sum def days_between_tdate(date1, date2):
y1 = int(date1[6:])
m1 = int(date1[3:5])
d1 = int(date1[:2]) if check_date_valid(y1, m1, d1) == -1:
return -1 y2 = int(date2[6:])
m2 = int(date2[3:5])
d2 = int(date2[:2]) if check_date_valid(y2, m2, d2) == -1:
return -1 return abs(calcu_days(y1, m1, d1) - calcu_days(y2, m2, d2)) def all_days_your_life(birthday):
date = raw_input("Enter the date of today:")
return days_between_tdate(birthday, date) def days_of_next_birthday(birthday):
date = raw_input("Enter the date of today:") y1 = int(date[6:])
m1 = int(date[3:5])
d1 = int(date[:2]) if check_date_valid(y1, m1, d1) == -1:
return -1 y2 = y1
m2 = int(birthday[3:5])
d2 = int(birthday[:2]) if check_date_valid(y2, m2, d2) == -1:
return -1 if calcu_days(y2,m2,d2)<calcu_days(y1,m1,d1):
y2 = y2 +1 return calcu_days(y2,m2,d2)-calcu_days(y1,m1,d1) date1 = raw_input("Enter the date1:")
date2 = raw_input("Enter the date2:") print "the days between these two date is: %d days"% days_between_tdate(date1, date2) birthday = raw_input("enter the date you have born:")
print "the days you have been in the world: %s days"% all_days_your_life(birthday) print "the next birthday till now: %d days"% days_of_next_birthday(birthday)

6-16

 #6-16

 def add_matrix(M, N):
r1 = len(M)
c1 = len(M[0]) r2 = len(N)
c2 = len(N[0]) r = [([0]*r1) for i in range(c1)] if r1==r2 and c1==c2:
i = 0
while i<r1:
j = 0
while j<c1:
r[i][j] = M[i][j] + N[i][j]
print M[i][j], N[i][j]
j = j+1
i = i+1
return r
else:
return -1 def mul_matrix(M, N):
r1 = len(M)
c1 = len(M[0]) r2 = len(N)
c2 = len(N[0]) if c1 != r2:
return -1
r = [([0]*c2) for i in range(r1)] for i in range(r1):
for j in range(c2):
for i1 in range(c1):
r[i][j] = r[i][j] + M[i][i1]*N[i1][j]
i1 = i1 + 1
j = j +1
i= i+1
return r M = [[1,1], [2,0]]
N = [[-1,2], [9,0]] print add_matrix(M, N)
N=[[0, 2, 3], [1, 1, 2]]
print mul_matrix(M, N)

6-17

 #6-17

 def myPop(a):
if len(a[0]) == 0:
return -1
ret = a[0][-1] #a[0] = a[0][0: len(a[0])-1]
del a[0][-1]
print a[0]
return ret a = [1,2,3] print myPop([a])
print a