《Python语言程序设计基础》课后习题程序整理(第5~7章)
程序大多数为自己编写,程序可能不是最优,复杂度不是最好,也有可能存在理解错题意的问题,敬请谅解。
习题内容为高等教育出版社出版的由嵩天教授等编写的《Python语言程序设计基础(第2版)》中的习题内容。
第五章 函数和代码复用
5.2 实现isOdd()函数,参数为整数,如果整数为奇数,返回True,否则返回False。
5.3 实现isNum()函数,参数为一个字符串,如果这个字符串属于整数、浮点数或复数的表示,则返回True,否则返回False。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
def isNum(num): if num.isnumeric(): return True #下面为判断是否为复数的一种方法 elif len(num)==len(set(num)): return True else: return False &nbsp; num = input("请输入字符串:") isnum = isNum(num) if isnum: print("你输入的字符串是数字!") else: print("你输入的字符串不是数字!") <strong>5.4 实现multi()函数,参数个数不限,返回所有参数的乘积。</strong> def multi(nums): ''' 计算传入数字之积 ''' m=1 for i in nums: m=m*i return m &nbsp; item_num1 = input("请输入数字,以空格分隔,若输入完成请按回车:") item_num = item_num1.split(' ') ls =[] for i in item_num: i = eval(i) ls.append(i) ans = multi(ls) print(ans) |
5.5 实现isPrime()函数,参数为整数,要有异常处理。如果整数是质数,返回True,否则返回False。
集中实现以上5.2、5.5的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
def isOdd(num): ''' 判断num数字是否是奇数,若是返回True,否则返回False ''' if num%2 ==1: return True else: return False &nbsp; def isPrime(num): ''' 判断是否是质数,若是则返回True,否则返回False ''' if num ==1: return False elif num ==2 or num ==3: return True else: for i in range(3,num): if(num%i == 0): return False return True &nbsp; &nbsp; def switFunction(item,num): ''' 选择所需要的功能并输出结果 ''' if(item == 1): ans = isOdd(num) if ans: print("{}是奇数".format(num)) else: print("{}不是奇数".format(num)) if(item == 2): ans = isPrime(num) if ans: print("{}是质数".format(num)) else: print("{}不是质数".format(num)) if(item!=1 and item!=2): print("请选择正确的功能") &nbsp; func_num = input("请选择你所需要的功能,1为判断奇数,2为判断质数:") func_num = eval(func_num) item_num = input("请输入你需要判断的数字:") item_num = eval(item_num) switFunction(func_num,item_num) <strong>5.7 汉诺塔问题。采用递归方法解决汉诺塔问题,要求输入汉诺塔的层数,输出整个移动流程。</strong> def move(n,a,b,c): if n==1: print(a,'--&gt;',c) else: move(n-1,a,c,b) #将前n-1个盘子从a移动到b上 move(1,a,b,c) #将最底下的最后一个盘子从a移动到c上 move(n-1,b,a,c) #将b上的n-1个盘子移动到c上 move(3,'A','B','C') |
第六章 组合数据类型
6.1 随机密码生成。编写程序,在26个字母大小写和9个数字组成的列表中随机生成10个8位密码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
#6.1 random password from random import choice def rand_pass(N): ls = []#create list #add alpha and number into list for i in range(97,123): ls.append(chr(i)) for i in range(65,91): ls.append(chr(i)) for i in range(48,58): ls.append(chr(i)) #build one password return ''.join(choice(ls) for i in range(N)) #produce ten passwords for i in range(10): ans_ls = rand_pass(8) print(ans_ls) |
6.2 重复元素判定。编写一个函数,接受列表作为参数,如果一个元素在列表中出现了不止一次,则返回True,但不要改变原来列表的值。同时编写调用这个函数和测试结果的程序。
6.3 利用集合的无重复性改编程序练习题6.2的程序,获得一个更快更简洁的版本。
6.2/6.3代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
def repDetermination_1(ls): ''' Determinant of repeated elements. If a list has repeated elements, return True. If it does not has, return False This is the Method ONE. ''' for i in range(len(ls)): for j in range(i+1,len(ls)): if ls[i] == ls[j]: return True return False &nbsp; def repDetermination_2(ls): ''' Determinant of repeated elements. If a list has repeated elements, return True. If it does not has, return False This is the Method TWO. ''' len_or = len(ls)# original list ls_set = len(set(ls))#after being a set #if the original list has repeated elements, the length will be different if len_or == ls_set: return False else: return True &nbsp; ls = input("请输入元素,以空格分隔。输入完毕,请按回车:\n") ls = ls.split(" ") ans_1 = repDetermination_1(ls) ans_2 = repDetermination_2(ls) print("方法一得到的结果是{};\n方法二得到的结果是:{}".format(ans_1,ans_2)) |
6.5 生日悖论分析。生日悖论指如果一个房间里有23人或以上,那么至少有两个人生日相同的概率大于50%。编写程序,输出在不同随机样本数量下,23个人中至少两个人生日相同的概率。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
import random &nbsp; def generate_birthday(stu_nums): ''' Generate the birthday of 23 students. ''' birth_date= [] for i in range(stu_nums): birth_date.append(random.randint(1,365)) return birth_date &nbsp; def equal_birthday(birth_date): x = birth_date[:] x.sort() for i in range(len(x)-1): if x[i] == x[i+1]: return True return False &nbsp; def birth_count(samples, stu_nums): count = 0 m = [] for i in range(samples): m = generate_birthday(stu_nums) if equal_birthday(m): count +=1 return count &nbsp; samples = input("请输入样本数:\n") samples = eval(samples) stu_nums = 0 while(stu_nums &lt;23): stu_nums = input("请输入人数,不得小于23,默认为23:\n") stu_nums = eval(stu_nums) count = birth_count(samples,stu_nums) rate = count/samples*100 print("概率为{:.2f}%".format(rate)) |
第七章:文件和数据格式化
7.1 Python源文件改写。编写一个程序,读取一个Python源程序文件,将文件中所有除保留字外的小写字母换成大写字母,生成后的文件要能够被Python解释器正确执行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
import keyword &nbsp; excludes = keyword.kwlist exclud = ['print','format'] fname = input("请输入要打开的文件(包含后缀名):\n") f = open(fname,'r').readlines() print(f) ls = [] for i in f: i = i.split(" ") ls.append(i) &nbsp; print(ls) #建立一个每行所有单词为一个元素的列表 new_name = input("请输入新建的文件的文件名(包含后缀名):\n") fo = open(new_name,'w+') for i in range(len(ls)): if f[i].isspace(): fo.write(" ") for j in range(len(ls[i])): x = ls[i][j] if x in excludes: x = x.lower() else: x = x.upper() if x ==ls[i][len(ls[i])-1]: fo.write(x +"\n") else: fo.write(x+" ") fo.close() print("处理结束!") |
程序仍然存在问题,例如range或者print因为和其它字符组成一个字符串,暂时想不到如何分割然后让其仍然小写。
7.2 图像文件压缩。使用PIL库对图片进行等比例压缩,无论压缩前文件大小如何,压缩后文件小于10KB。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
from PIL import Image def resizeImg(ori_name, des_name, dst_w, dst_h, save_q): im = Image.open(ori_name) ori_w,ori_h = im.size widthRatio = heightRatio = None ratio = 1 if(ori_w and ori_w&gt;dst_w) or (ori_h and ori_h &gt;dst_h): if dst_w and ori_w&gt;dst_w: widthRatio = float(dst_w/ori_w) if dst_h and ori_h&gt;dst_h: heightRatio = float(dst_h/ori_h) &nbsp; if widthRatio and heightRatio: if heightRatio &lt; widthRatio: ratio = heightRatio else: ratio = widthRatio if widthRatio and not heightRatio: ratio = widthRatio if heightRatio and not widthRatio: ratio = heightRatio newWidth = int(ori_w *ratio) newHeight = int(ori_h *ratio) else: newWidth = ori_w newHeight = ori_h &nbsp; im.resize((newWidth,newHeight),Image.ANTIALIAS).save(des_name, quality=save_q) &nbsp; ori_name = '1.jpg' des_name = '1_modify.jpg' dst_w = 300 dst_h = 300 save_q = 50 resizeImg(ori_name, des_name, dst_w, dst_h, save_q) |