python综合小测 python综合设计问题_python综合小测

《python程序设计》习题与答案

《Python 程序设计》习题与参考答案第 1 章 基础知识1.1 简单说明如何选择正确的 Python 版本。答:在选择 Python 的时候,一定要先考虑清楚自己学习 Python 的目的是什么,打算做哪方面的开发,有哪些扩展库可用,这些扩展库最高支持哪个版本的 Python,是 Python 2.x还是 Python 3.x,最高支持到 Python 2.7.6 还是 Python 2.7.9。这些问题都确定以后,再做出自己的选择,这样才能事半功倍,而不至于把大量时间浪费在 Python 的反复安装和卸载上。同时还应该注意,当更新的 Python 版本推出之后,不要急于更新,而是应该等确定自己所必须使用的扩展库也推出了较新版本之后再进行更新。尽管如此,Python 3 毕竟是大势所趋,如果您暂时还没想到要做什么行业领域的应用开发,或者仅仅是为了尝试一种新的、好玩的语言,那么请毫不犹豫地选择 Python 3.x 系列的最高版本(目前是 Python 3.4.3) 。1.2 为什么说 Python 采用的是基于值的内存管理模式?答:Python 采用的是基于值的内存管理方式,如果为不同变量赋值相同值,则在内存中只有一份该值,多个变量指向同一块内存地址,例如下面的代码。>>> x = 3>>> id(x)10417624>>> y = 3>>> id(y)10417624>>> y = 5>>> id(y)10417600>>> id(x)104176241.3 在 Python 中导入模块中的对象有哪几种方式?答:常用的有三种方式,分别为 import 模块名 [as 别名] from 模块名 import 对象名 [ as 别名] from math import *1.4 使用 pip 命令安装 numpy、scipy 模块。答:在命令提示符环境下执行下面的命令:pip install numpypip install scipy1.5 编写程序,用户输入一个三位以上的整数,输出其百位以上的数字。例如用户输入 1234,则程序输出 12。 (提示:使用整除运算。 )答:1)Python 3.4.2 代码:x = ( Please an integer of more than 3 digits: )try:x = int(x)x = x//100if x == 0:print( You must an integer of more than 3 digits. )else:print(x)except BaseException:print( You must an integer. )2)Python 2.7.8 代码:import typesx = ( Please an integer of more than 3 digits: )if type(x) != types.IntType:print You must an integer. elif len(str(x)) != 4:print You must an integer of more than 3 digits. else:print x//100第 2 章 Python 数据结构2.1 为什么应尽量从列表的尾部进行元素的增加与删除操作?答:当列表增加或删除元素时,列表对象自动进行内存扩展或收缩,从而保证元素之间没有缝隙,但这涉及到列表元素的移动,效率较低,应尽量从列表尾部进行元素的增加与删除操作以提高处理速度。2.2 编写程序,生成包含 1000 个 0 到 100 之间的随机整数,并统计每个元素的出现次数。 (提示:使用集合。 )答:1)Python 3.4.2 代码import randomx = [random.randint(0,100) for i in range(1000)]d = set(x)for v in d:print(v, : , x.count(v))2)Python 2.7.8 代码import randomx = [random.randint(0,100) for i in range(1000)]d = set(x)for v in d:print v, : , x.count(v)2.3 编写程序,用户输入一个列表和 2 个整数作为下标,然后输出列表中介于 2 个下标之间的元素组成的子列表。例如用户输入[1,2,3,4,5,6]和 2,5,程序输出[3,4,5,6] 。答:1)Python 3.4.2 代码x = ( Please a list: )x = (x)start, end = (( Please the start position and the end position: ))print(x[start:end])2)Python 2.7.8 代码x = ( Please a list: )start, end = ( Please the start position and the end position: )print x[start:end]2.4 设计一个字典,并编写程序,用户输入内容作为键,然后输出字典中对应的值,如果用户输入的键不存在,则输出“您输入的键不存在!”答:1)Python 3.4.2 代码d = {1: a , 2: b , 3: c , 4: d }v = ( Please a key: )v = (v)print(d.get(v, 您输入的的键不存在 ))2)Python 2.7.8 代码d = {1: a , 2: b , 3: c , 4: d }v = ( Please a key: )print(d.get(v, 您输入的的键不存在 ))2.5 编写程序,生成包含 20 个随机数的列表,然后将前 10 个元素升序排列,后 10 个元素降序排列,并输出结果。答:1)Python 3.4.2 代码import randomx = [random.randint(0,100) for i in range(20)]print(x)y = x[0:10]y.sort()x[0:10] = yy = x[10:20]y.sort(reverse=True)x[10:20] = yprint(x)2)Python 2.7.8 代码import randomx = [random.randint(0,100) for i in range(20)]print xy = x[0:10]y.sort()x[0:10] = yy = x[10:20]y.sort(reverse=True)x[10:20] = yprint x2.6 在 Python 中,字典和集合都是用一对 大括号 作为定界符,字典的每个元素有两部分组成,即 键 和 值 ,其中