小奥的学习笔记

  • Home
  • Learning & Working
    • Speech Enhancement Notes
    • Programming language
    • Computer & DL
    • MOOC
  • Life
    • Life Time
    • Thinking & Comprehension
    • Volunteer
    • Plan
    • Travel
  • Footprints
  • GuestBook
  • About
    • About Me
    • 个人履历
    • 隐私策略
  1. 首页
  2. Study-notes
  3. Programming language
  4. Python
  5. 正文

《Python语言程序设计基础》课后习题程序整理(第5~7章)

2018年5月22日 12436点热度 0人点赞 0条评论

程序大多数为自己编写,程序可能不是最优,复杂度不是最好,也有可能存在理解错题意的问题,敬请谅解。

习题内容为高等教育出版社出版的由嵩天教授等编写的《Python语言程序设计基础(第2版)》中的习题内容。

第五章 函数和代码复用

5.2 实现isOdd()函数,参数为整数,如果整数为奇数,返回True,否则返回False。

5.3 实现isNum()函数,参数为一个字符串,如果这个字符串属于整数、浮点数或复数的表示,则返回True,否则返回False。

def isNum(num):

if num.isnumeric():

return True

#下面为判断是否为复数的一种方法

elif len(num)==len(set(num)):

return True

else:

return False

 

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的代码:

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位密码。

#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代码如下:

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个人中至少两个人生日相同的概率。

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解释器正确执行。

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。

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)
本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: Python python学习
最后更新:2018年5月22日

davidcheung

这个人很懒,什么都没留下

打赏 点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

搜索
欢迎关注我的个人公众号
最新 热点 随机
最新 热点 随机
DEEPFILTERNET:一种基于深度滤波的全频带音频低复杂度语音增强框架 奥地利匈牙利九日游旅程 论文阅读之Study of the General Kalman Filter for Echo Cancellation 小奥看房之鸿荣源珈誉府 杭州往返旅途及西溪喜来登和万怡的体验报告 2022年的第一篇碎碎念
奥地利匈牙利九日游旅程论文阅读之Study of the General Kalman Filter for Echo CancellationDEEPFILTERNET:一种基于深度滤波的全频带音频低复杂度语音增强框架
Leetcode题目解析(191217):20&22&32 中华帝国没落史 作品声明 《优化阵列信号处理》学习笔记(第四章) 新青年报[合集]发布! 关于更新github、微信公众号和博客周期的说明
标签聚合
leetcode linux 学习 鸟哥的linux私房菜 高中 算法 Python 生活 Java python学习
最近评论
davidcheung 发布于 5 个月前(02月09日) The problem has been fixed. May I ask if you can s...
tk88 发布于 5 个月前(02月07日) Hmm is anyone else having problems with the pictur...
cuicui 发布于 9 个月前(10月20日) :wink:
niming 发布于 10 个月前(09月19日) 同级校友,能刷到太巧了
davidcheung 发布于 2 年前(08月16日) 我得找一下我之前整理的word文档看一下,如果找到了我就更新一下这篇文章。
Nolan 发布于 2 年前(07月25日) 您的笔记非常有帮助。贴图不显示了,可以更新一下吗?
davidcheung 发布于 3 年前(06月19日) 到没有看webrtc的代码。现在主要在看我们公司的代码了。。。只是偶尔看一看webrtc的东西。。。
aobai 发布于 3 年前(03月13日) gain_change_hangover_ 应该是每三个block 只能够调整一次,这样保证每帧...
匿名 发布于 5 年前(12月30日) 烫
小奥 发布于 5 年前(12月12日) webRTC里面的NS本身我记得就是在C++里面呀

COPYRIGHT © 2025 小奥的学习笔记. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

陕ICP备19003234号-1

鲁公网安备37120202000100号