python核心编程第六章答案
python核心编程第二版第6章习题答案

6-1.字符串。
string模块中是否有一种字符串方法或者函数可以帮我鉴定下一个字符串是否是另一个大字符串的一部分?答案:成员操作符用于判断一个字符或者一个字串(中的字符)是否出现在另一个字符串中。
出现则返回True,否者返回False。
注意,成员操作符不是用来判断一个字符串是否包含另一个字符串的,这样的功能由find(),index(),rfind()和rindex()函数来完成。
>>> 'bc' in 'abcd'True>>> 'n' in 'abcd'False6-2.字符串标识符。
修改例6-1的idcheck.py脚本,使之可以检测长度为一的标识符,并且可以识别Python关键字。
对后一个要求,你可以使用keyword模块(特别是keyword.kwlist)来辅助。
答案:#!/usr/bin/env pythonimport stringimport keywordalphas = string.letters + '_'nums = string.digitskeywords = keyword.kwlistprint "Welcome to the Identifier Checker v1.0"myInput = raw_input('Identifier to test? >>')if myInput in keywords:print 'Invalid: It is a keyword.'else:if myInput[0] not in alphas:print '''invalid: first sysmol must be alphabetic'''else:for otherChar in myInput[1:]:if otherChar not in alphas + nums:print '''invalid: remaining sysmols must be alphabetic'''breakelse:print "okay as an identifier"6-3.排序。
python第6章字典课后习题答案

Solutions - Chapter 66-1: PersonUse a dictionary to store information about a person you know. Store their first name, last name, age, and the city in which they live. You should have keys such as first_name, last_name, age, and city. Print each piece of information stored in your dictionary.Output:6-2: Favorite NumbersUse a dictionary to store people’s favorite numbers. Think of five names, and use them as keys in your dictionary. Think of a favorite number for each person, and store each as a value in your dictionary. Print each person’s name and their favorite number. For even more fun, poll a few friends and get some actual data for your program.Output:6-3: GlossaryA Python dictionary can be used to model an actual dictionary. However, to avoid confusion, let’s call it a glossary.Think of five programming words you’ve learned about in the previous chapters. Use these words as the keys in yourglossary, and store their meanings as values.Print each word and its meaning as neatly formatted output.You might print the word followed by a colon and then itsmeaning, or print the word on one line and then print itsmeaning indented on a second line. Use the newline character ('\n') to insert a blank line between each word-meaning pair in your output.Output:6-4: Glossary 2Now that you know how to loop through a dictionary, clean up the code from Exercise 6-3 (page 102) by replacing your seriesof print statements with a loop that runs through the dictionary’s keysand values. When you’re sure that your loop works, add five more Python terms to your glossary. When you run your program again, these new words and meanings should automatically be included in the output.Output:6-5: RiversMake a dictionary containing three major rivers and the country each river runs through. One key-value pair might be 'nile': 'egypt'.∙Use a loop to print a sentence about each river, such as The Nile runs through Egypt.∙Use a loop to print the name of each river included in the dictionary.∙Use a loop to print the name of each country included in the dictionary.Output*:*Sometimes we like to think of Alaska as our own separate country.6-6: PollingUse the code in favorite_languages.py (page 104).∙Make a list of people who should take the favorite languages poll. Include some names that are already in the dictionary and some that are not.∙Loop through the list of people who should take the poll. If they have already taken the poll, print a message thanking them for responding. If they have not yet taken the poll, print a message inviting them to take the poll.Output:6-7: PeopleStart with the program you wrote for Exercise 6-1 (page 102). Make two new dictionaries representing different people, and store all three dictionaries in a list called people. Loop through your list of people. As you loop through the list, print everything you know about each person.Output:6-8: PetsMake several dictionaries, where the name of each dictionary is the name of a pet. In each dictionary, include the kind of animal and the owner’s name. Store these dictionaries in a list called pets. Next, loop through your list and as you do print everything you know about each pet.Output:6-9: Favorite PlacesMake a dictionary called favorite_places. Think of three names touse as keys in the dictionary, and store one to three favorite places for each person. To make this exericse a bit more interesting, ask somefriends to name a few of their favorite places. Loop through the dictionary, and print each person’s name and their favorite places.Output:6-10: Favorite NumbersModify your program from Exercise 6-2 (page 102) so each person can have more than one favorite number. Then print each person’s name along with their favorite numbers.Output:6-11: CitiesMake a dictionary called cities. Use the names of three cities askeys in your dictionary. Create a dictionary of information about each city and include the country that the city is in, its approximate population, and one fact about that city. The keys for each city’s dictionary should be something like country, population, and fact.Print the name of each city and all of the information you have stored about it.Output:。
《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 = input('Please input an integer of more than 3 digits:')try:x = int(x)x = x//100if x == 0:print('You must input an integer of more than 3 digits.')else:print(x)except BaseException:print('You must input an integer.')2)Python 2.7.8代码:import typesx = input('Please input an integer of more than 3 digits:')if type(x) != types.IntType:print 'You must input an integer.'elif len(str(x)) != 4:print 'You must input an integer of more than 3 digits.'else:print x//100第2章 Python数据结构2.1 为什么应尽量从列表的尾部进行元素的增加与删除把持?答:当列表增加或删除元素时,列表对象自动进行内存扩展或收缩,从而保证元素之间没有缝隙,但这涉及到列表元素的移动,效率较低,应尽量从列表尾部进行元素的增加与删除把持以提高处置速度.2.2 编写法式,生成包括1000个0到100之间的随机整数,并统计每个元素的呈现次数.(提示:使用集合.)答:import randomx = [random.randint(0,100) for i in range(1000)]d = set(x)for v in d:print(v, ':', x.count(v))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].答:x = input('Please input a list:')x = eval(x)start, end = eval(input('Please input the start position and the end position:'))print(x[start:end])x = input('Please input a list:')start, end = input('Please input the start position and the end position:')print x[start:end]2.4 设计一个字典,并编写法式,用户输入内容作为键,然后输出字典中对应的值,如果用户输入的键不存在,则输出“您输入的键不存在!”答:d = {1:'a', 2:'b', 3:'c', 4:'d'}v = input('Please input a key:')v = eval(v)print(d.get(v,'您输入的的键不存在'))d = {1:'a', 2:'b', 3:'c', 4:'d'}v = input('Please input a key:')print(d.get(v,'您输入的的键不存在'))2.5 编写法式,生成包括20个随机数的列表,然后将前10个元素升序排列,后10个元素降序排列,并输出结果.答: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)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中,字典和集合都是用一对年夜括号作为定界符,字典的每个元素有两部份组成,即键和值 ,其中键不允许重复.2.7 假设有列表 a = ['name','age','sex']和 b = ['Dong',38,'Male'],请使用一个语句将这两个列表的内容转换为字典,而且以列表a中的元素为键,以列表b中的元素为值,这个语句可以写为 c = dict(zip(a,b)).2.8 假设有一个列表a,现要求从列表a中每3个元素取1个,而且将取到的元素组成新的列表b,可以使用语句 b = a[::3].2.9 使用列表推导式生成包括10个数字5的列表,语句可以写为 [5 for i in range(10)].2.10 不成以(可以、不成以)使用del命令来删除元组中的部份元素.第3章选择结构与循环结构3.1 分析逻辑运算符“or”的短路求值特性.答:假设有表达式“表达式1 or 表达式2”,如果表达式1的值等价于True,那么无论表达式2的值是什么,整个表达式的值总是等价于True.因此,不需要再计算表达式2的值.3.2 编写法式,运行后用户输入4位整数作为年份,判断其是否为闰年.如果年份能被400整除,则为闰年;如果年份能被4整除但不能被100整除也为闰年.答:x = input('Please input an integer of 4 digits meaning the year:')x = eval(x)if x%400==0 or (x%4==0 and not x%100==0):print('Yes')else:print('No')x = input('Please input an integer of 4 digits meaning the year:')if x%400==0 or (x%4==0 and not x%100==0):print 'Yes'else:print 'No'3.3 编写法式,生成一个包括50个随机整数的列表,然后删除其中所有奇数.(提示:从后向前删.)答:import randomx = [random.randint(0,100) for i in range(50)]print(x)i = len(x)-1while i>=0:if x[i]%2==1:del x[i]i-=1print(x)把上面的代码中第三行和最后一行改为print x即可.34 编写法式,生成一个包括20个随机整数的列表,然后对其中偶数下标的元素进行降序排列,奇数下标的元素不变.(提示:使用切片.)答:import randomx = [random.randint(0,100) for i in range(20)]print(x)y = x[::2]y.sort(reverse=True)x[::2] = yprint(x)把上面的代码中第三行和最后一行改为print x即可.35 编写法式,用户从键盘输入小于1000的整数,对其进行因式分解.例如,10=2×5,60=2×2×3×5.答:x = input('Please input an integer less than 1000:')x = eval('x')t = xi = 2result = []while True:if t==1:breakif t%i==0:result.append(i)t = t/ielse:i+=1Print x,'=','*'.join(map(str,result))x = input('Please input an integer less than 1000:')t = xi = 2result = []while True:if t==1:breakif t%i==0:result.append(i)t = t/ielse:i+=1print x,'=','*'.join(map(str,result))3.6 编写法式,至少使用2种分歧的方法计算100以内所有奇数的和.答:Python 3.4.2代码如下,如果使用Python 2.7.8只需要把其中的print()函数改为print语句即可.x = [i for i in range(1,100) if i%2==1]print(sum(x))print(sum(range(1,100)[::2]))3.7 编写法式,实现分段函数计算,如下表所示.答:Python 3.4.2代码如下,如果使用Python 2.7.8只需要把其中的print()函数改为print语句即可.x = input('Please input x:')x = eval(x)if x<0 or x>=20:print(0)elif 0<=x<5:print(x)elif 5<=x<10:print(3*x-5)elif 10<=x<20:print(0.5*x-2)第4章字符串与正则表达式4.1 假设有一段英文,其中有独自的字母“I”误写为“i”,请编写法式进行纠正.答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可.1)不使用正则表达式x = "i am a teacher,i am man, and i am 38 years old.I am not a businessman."x = x.WordStr('i ','I ')x = x.WordStr(' i ',' I ')print(x)2)使用正则表达式x = "i am a teacher,i am man, and i am 38 years old.I am not a businessman."import repattern = pile(r'(?:[^\w]|\b)i(?:[^\w])')while True:result = pattern.search(x)if result:if result.start(0) != 0:x = x[:result.start(0)+1]+'I'+x[result.end(0)-1:]else:x = x[:result.start(0)]+'I'+x[result.end(0)-1:]else:breakprint(x)4.2 假设有一段英文,其中有单词中间的字母“i”误写为“I”,请编写法式进行纠正.答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可.import rex = "I am a teacher,I am man, and I am 38 years old.I am not a busInessman."print(x)pattern = pile(r'(?:[\w])I(?:[\w])')while True:result = pattern.search(x)if result:if result.start(0) != 0:x = x[:result.start(0)+1]+'i'+x[result.end(0)-1:]else:x = x[:result.start(0)]+'i'+x[result.end(0)-1:]else:breakprint(x)4.3 有一段英文文本,其中有单词连续重复了2次,编写法式检查重复的单词并只保管一个.例如文本内容为“This is is a desk.”,法式输出为“This is a desk.”答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可.1)方法一import rex = 'This is a a desk.'pattern = pile(r'\b(\w+)(\s+\1){1,}\b') matchResult = pattern.search(x)x = pattern.sub(matchResult.group(1),x)print(x)2)方法二x = 'This is a a desk.'pattern = pile(r'(?P<f>\b\w+\b)\s(?P=f)') matchResult = pattern.search(x)x = x.WordStr(matchResult.group(0),matchResult.group(1))4.4 简单解释Python的字符串驻留机制.答:Python支持字符串驻留机制,即:对短字符串,将其赋值给多个分歧的对象时,内存中只有一个副本,多个对象共享该副本.这一点不适用于长字符串,即长字符串不遵守驻留机制,下面的代码演示了短字符串和长字符串在这方面的区别.>>> a = '1234'>>> b = '1234'>>> id(a) == id(b)True>>> a = '1234'*50>>> b = '1234'*50>>> id(a) == id(b)False4.5 编写法式,用户输入一段英文,然后输出这段英文中所有长度为3个字母的单词.答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可.import rex = input('Please input a string:')pattern = pile(r'\b[a-zA-Z]{3}\b')print(pattern.findall(x))第5章函数设计与使用5.1 运行5.3.1小节最后的示例代码,检查结果并分析原因.答:原因是对函数的默认值参数只会被处置一次,下次再调用函数而且不为默认值参数赋值时会继续使用上一次的结果,对列表这样的结构,如果调用函数时为默认值参数的列表拔出或删除元素,将会获得保管,从而影响下一次调用.5.2 编写函数,判断一个整数是否为素数,并编写主法式调用该函数.答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可.import mathdef IsPrime(v):n = int(math.sqrt(v)+1)for i in range(2,n):if v%i==0:return 'No'else:return 'Yes'print(IsPrime(37))print(IsPrime(60))print(IsPrime(113))5.3 编写函数,接收一个字符串,分别统计年夜写字母、小写字母、数字、其他字符的个数,并以元组的形式返回结果.答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可.def demo(v):capital = little = digit = other =0for i in v:if 'A'<=i<='Z':capital+=1elif 'a'<=i<='z':little+=1elif '0'<=i<='9':digit+=1else:other+=1return (capital,little,digit,other)x = 'capital = little = digit = other =0'print(demo(x))5.4 在Python法式中,局部变量会隐藏同名的全局变量吗?请编写代码进行验证.谜底:会.>>> def demo():a=3print a>>> a=5>>> demo()3>>> a55.5 编写函数,可以接收任意多个整数并输出其中的最年夜值和所有整数之和.答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可.def demo(*v):print(v)print(max(v))print(sum(v))demo(1,2,3)demo(1,2,3,4)demo(1,2,3,4,5)5.6 编写函数,模拟内置函数sum().答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可.def Sum(v):s = 0for i in v:s += ireturn sx = [1,2,3,4,5]print(Sum(x))x = (1,2,3,4,5)print(Sum(x))5.7 编写函数,模拟内置函数sorted().答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可.def Sorted(v):t = v[::]r = []while t:tt = min(t)r.append(tt)t.remove(tt)return rx = [1,3,5,2,1,0,9,7]print(x)print(Sorted(x))第6章面向对象法式设计6.1 继承6.5节例2中的Person类生成Student类,填写新的函数用来设置学生专业,然后生成该类对象并显示信息.import typesclass Person(object): #基类必需继承于object,否则在派生类中将无法使用super()函数def __init__(self, name = '', age = 20, sex = 'man'): self.setName(name)self.setAge(age)self.setSex(sex)def setName(self, name):if not isinstance(name,str):print('name must be string.')returnself.__name = namedef setAge(self, age):if not isinstance(age,int):print('age must be integer.')returnself.__age = agedef setSex(self, sex):if sex != 'man' and sex != 'woman':print('sex must be "man" or "woman"')returnself.__sex = sexdef show(self):print(self.__name)print(self.__age)print(self.__sex)class Student(Person):def __init__(self, name='', age = 30, sex = 'man', major = 'Computer'):#调用基类构造方法初始化基类的私有数据成员super(Student, self).__init__(name, age, sex)self.setMajor(major) #初始化派生类的数据成员def setMajor(self, major):if not isinstance(major, str):print('major must be a string.')returnself.__major = majordef show(self):super(Student, self).show()print(self.__major)if __name__ =='__main__':zhangsan = Person('Zhang San', 19, 'man')zhangsan.show()lisi = Student('Li Si',32, 'man', 'Math')lisi.show()6.2 设计一个三维向量类,并实现向量的加法、减法以及向量与标量的乘法和除法运算.class Vecter3:def __init__(self, x=0, y=0, z=0):self.X = xself.Y = yself.Z = zdef __add__(self, n):r = Vecter3()return rdef __sub__(self, n):r = Vecter3()return rdef __mul__(self, n):r = Vecter3()r.X = self.X * nr.Y = self.Y * nr.Z = self.Z * nreturn rdef __truediv__(self, n):r = Vecter3()r.X = self.X / nr.Y = self.Y / nr.Z = self.Z / nreturn rdef __floordiv__(self, n):r = Vecter3()r.X = self.X // nr.Y = self.Y // nr.Z = self.Z // nreturn rdef show(self):print((self.X,self.Y,self.Z))v1 = Vecter3(1,2,3)v2 = Vecter3(4,5,6)v3 = v1+v2v3.show()v4 = v1-v2v4.show()v5 = v1*3v5.show()v6 = v1/2v6.show()6.3 面向对象法式设计的三要素分别为封装、继承和多态 .6.4 简单解释Python中以下划线开头的变量名特点.答:在Python中,以下划线开头的变量名有特殊的含义,尤其是在类的界说中.用下划线作为变量前缀和后缀来暗示类的特殊成员:●_xxx:这样的对象叫做呵护变量,不能用'from moduleimport *'导入,只有类对象和子类对象能访问这些变量;●__xxx__:系统界说的特殊成员名字;●__xxx:类中的私有成员,只有类对象自己能访问,子类对象也不能访问到这个成员,但在对象外部可以通过“”这样的特殊方式来访问.Python中没有纯洁的C++意义上的私有成员.6.5 与运算符“**”对应的特殊方法名为__pow__(),与运算符“//”对应的特殊方法名为 __floordiv__() .第7章文件把持7.1 假设有一个英文文本文件,编写法式读取其内容,并将其中的年夜写字母酿成小写字母,小写字母酿成年夜写字母.答:f = open(r'd:\1.txt','r')s = f.readlines()f.close()r = [i.swapcase() for i in s]f = open(r'd:\2.txt','w')f.writelines(r)f.close()7.2 编写法式,将包括学生成果的字典保管为二进制文件,然后再读取内容并显示.import pickled = {'张三':98,'李四':90,'王五':100}print(d)f = open('score.dat','wb')pickle.dump(1,f)pickle.dump(d,f)f = open('score.dat','rb')pickle.load(f)d = pickle.load(f)f.close()print(d)7.3 使用shutil模块中的move()方法进行文件移动.答:>>> import shutil>>> shutil.move(r'd:\1.txt', r'e:\1.txt')'e:\\1.txt'7.4 简单解释文本文件与二进制文件的区别.答:(1)文本文件文本文件存储的是惯例字符串,由若干文本行组成,通常每行以换行符'\n'结尾.惯例字符串是指记事本或其他文本编纂器能正常显示、编纂而且人类能够直接阅读和理解的字符串,如英文字母、汉字、数字字符串.文本文件可以使用字处置软件如gedit、记事本进行编纂.(2)二进制文件二进制文件把对象内容以字节串(bytes)进行存储,无法用记事本或其他普通字处置软件直接进行编纂,通常也无法被人类直接阅读和理解,需要使用专门的软件进行解码后读取、显示、修改或执行.罕见的如图形图像文件、音视频文件、可执行文件、资源文件、各种数据库文件、各类office文档等都属于二进制文件.7.5 编写代码,将以后工作目录修改为“c:\”,并验证,最后将以后工作目录恢复为原来的目录.答:>>> import os>>> os.getcwd()。
XX医学院本科各专业《Python》第六章习题与答案-2020年精品

XX医学院本科各专业《Python》第六章习题与答案一、选择题*1. (1,2,3)*3的执行结果是哪个?AA.(1,2,3,1,2,3,1,2,3)B.(1,2,3)(1,2,3)(1,2,3)C.(3,6,9)D. 出错*2.S和T是两个集合,哪个选项对S^T的描述是正确的?DA. S和T的并运算,包括在集合S和T的所有元素B. S和T的差运算,包括在集合S但不在T中的元素C. S和T的交运算,包括同时在集合S和T中的元素D. S和T的补运算,包括集合S和T中的非相同元素*3. S和T是两个集合,哪个选项对S-T的描述是正确的?BA. S和T的并运算,包括在集合S和T的所有元素B. S和T的差运算,包括在集合S但不在T中的元素C. S和T的交运算,包括同时在集合S和T中的元素D. S和T的补运算,包括集合S和T中的非相同元素*4. S是一个集合,哪个选项关于S.pop( )的说法是错误的?BA. 默认情况下,随机取回集合S中的一个元素B. 当给定参数时,S.pop(i)取回集合S中序号为i的元素C. 调用S.pop( )之后,取回的元素将在S中删除D. 如果S为空,调用S.pop( )之后产生KeyError异常*5. 对于序列s,哪个选项能够返回序列s中第i到j以k为步长的元素子序列?CA. s[i,j,k]B. s[i;j;k]C. s[i:j:k]D. s(i,j,k)*6. 序列s,哪个选项对s.index(x)的描述是正确的?CA. 返回序列s中序号为x的元素B.返回序列s中元素x所有出现位置的序号C.返回序列s中元素x第一次出现的序号D.返回序列s中x的长度*7. 元组变量t=(“cat”,”dog”,”tiger”,”human”),哪个选项是t[::-1]的结果?AA. (‘human’,’tiger’,’dog’,’cat’)B. [‘human’,’tiger’,’dog’,’cat’]C.{ ‘human’,’tiger’,’dog’,’cat’}D. 运行出错*8. 列表ls,哪个选项对ls.append(x)的描述是正确的?BA. 向ls中增加元素,如果x是一个列表,则可以同时增加多个元素B. 只能向列表ls最后增加一个元素xC. 向列表ls最前面增加一个元素xD. 替换列表ls最后一个元素为x*9. 列表ls,哪个选项对ls.reverse( )的描述是正确的?BA. 将ls中元素逆序,返回一个新列表B. 将ls中元素逆序,更新列表lsC. 将ls中可以比较的元素进行逆序处理D. 如果ls为空,则产生一个异常*10. 哪个选项能够向列表ls中增加五个元素?CA. ls.append([1,2,3,4,5])B.ls.append(1,2,3,4,5)C.ls+=1,2,3,4,5D. ls.insert(1,2,3,4,5)*11. 那个选项不能生成一个空字典?DA.{}B.dict( )C.dict([ ])D. {[ ]}*12. 给定字典d,哪个选项对d.keys( )的描述是正确的?AA. 返回一种dict_keys类型,包括字典d中所有键B. 返回一个列表类型,包括字典d中所有键C.返回一个元组类型,包括字典d中所有键D. 返回一个集合类型,包括字典d中所有键*13. 给定字典d,哪个选项对d.values( )的描述是正确的?AA. 返回一种dict_values类型,包括字典d中所有值B. 返回一个列表类型,包括字典d中所有值C. 返回一个元组类型,包括字典d中所有值D. 返回一个集合类型,包括字典d中所有值*14. 给定字典d,哪个选项对d.items( )的描述是正确的?AA. 返回一种dict_items类型,包括字典d中所有键值对B. 返回一个列表类型,每个元素是一个二元元组,包括字典d中所有键值对C. 返回一个元组类型,每个元素是一个二元元组,包括字典d中所有键值对D. 返回一个集合类型,每个元素是一个二元元组,包括字典d中所有键值对*15. 给定字典d,哪个选项对d.get(x,y )的描述是正确的?BA. 返回字典d中键值对为x:y的值B. 返回字典d中键值为x的值,如果不存在,则返回yC. 返回字典d中键值为x的值,如果不存在,则返回空D. 返回字典d中键值为y的值,如果不存在,则返回x*16. 给定字典d,哪个选项对x in d的描述是正确的?BA. x是一个二元元组,判断x是否是字典d中的键值对B. 判断x是否是字典d中的键C. 判断x是否是字典d中的值D. 判断x是否是在字典d中以键或值方式存在*17.给定字典d,哪个选项可以清空该字典并保留变量?CA.d.remove( )B.d.pop( )C.d.clear( )D. del d*18.以下不能创建一个字典的语句是:AA. dict1={[1,2,3]:”aksd”}B. dict1={}C.dict1={(1,2,3):”aksd”}D. dict1={3:5} *19.哪个选项是下面代码的输出结果?Cd={‘a’:1,’b’:2,’b’:’3’}print(d[‘b’])A. 1B. 2C. 3D. {‘b’:2}*20. 关于大括号{},以下描述正确的是:CA. 直接使用{}将生成一个集合类型B. 直接使用{}将生成一个列表类型C. 直接使用{}将生成一个字典类型D. 直接使用{}将生成一个元组类型21.表达式[1, 2, 3,4]*3的执行结果为(A)。
python第六章课后编程题

python第六章课后编程题1. 对于Python第六章的课后编程题,我们将通过以下几个问题来进行讨论和解答。
问题一:如何在Python中进行字符串的索引和切片操作?在Python中,我们可以使用索引和切片对字符串进行操作。
字符串的索引是从0开始的,我们可以使用方括号[]来获取字符串中特定位置的字符。
例如,对于字符串"Hello World",我们可以通过"Hello World"[0]来获取第一个字符"H"。
字符串的切片操作可以获取字符串的一部分,语法为[start:end]。
其中,start表示起始位置,end表示结束位置(不包含该位置)。
例如,"Hello World"[0:5]将返回"Hello","[6:]"将返回"World"。
问题二:如何将一个字符串反转?要将一个字符串反转,我们可以使用切片的负数索引。
正数索引从左到右,而负数索引则从右到左。
例如,"Hello World"[::-1]将返回"dlroW olleH",即将字符串完全反转。
问题三:如何统计一个字符串中特定字符的出现次数?Python提供了count()函数来统计字符串中特定字符的出现次数。
语法为:字符串.count(字符)。
例如,"Hello World".count("o")将返回2,即统计字符串中字符"o"的出现次数。
问题四:如何将一个字符串按照特定分隔符拆分成多个子串?Python提供了split()函数来按照特定字符或字符串分隔符拆分一个字符串。
语法为:字符串.split(分隔符)。
例如,"Hello World".split(" ")将返回一个包含两个元素的列表,即["Hello", "World"]。
python核心编程参考答案

python核心编程参考答案Python核心编程参考答案Python是一种易于学习且功能强大的编程语言,广泛应用于软件开发、数据分析和人工智能等领域。
对于初学者来说,学习Python可能会遇到一些难题,需要参考一些权威的资料和答案来解决问题。
本文将提供一些Python核心编程的参考答案,帮助读者更好地理解和运用Python。
1. 数据类型与运算Python中常见的数据类型包括整数、浮点数、字符串、列表、元组和字典等。
对于不同的数据类型,有不同的操作和运算方法。
以下是一些常见问题的参考答案:- 如何将字符串转换为整数或浮点数?使用int()函数可以将字符串转换为整数,使用float()函数可以将字符串转换为浮点数。
- 如何将整数或浮点数转换为字符串?使用str()函数可以将整数或浮点数转换为字符串。
- 如何对列表进行排序?使用sort()方法可以对列表进行排序,例如:list.sort()。
- 如何获取列表的长度?使用len()函数可以获取列表的长度,例如:len(list)。
2. 控制流程与循环控制流程和循环是编程中常用的结构,用于控制程序的执行流程和重复执行某些操作。
以下是一些常见问题的参考答案:- 如何使用if语句进行条件判断?if语句用于根据条件执行不同的代码块。
例如:```if condition:# do somethingelse:# do something else```- 如何使用for循环遍历列表?for循环用于遍历列表中的元素。
例如:```for item in list:# do something with item```- 如何使用while循环进行迭代操作?while循环用于根据条件重复执行某些操作。
例如:```while condition:# do something```3. 函数与模块函数和模块是Python中组织和重用代码的重要方式。
以下是一些常见问题的参考答案:- 如何定义和调用函数?使用def关键字定义函数,使用函数名和参数调用函数。
python第六章课后编程题

Python语言程序设计(美-梁勇)第6章习题解答(英文)Python语言程序设计(第6章函数6.1使用函数的好处是什么?答:至少有三个好处:(1)重用代码(2)减少复杂性(3)易于维护6.2如何定义一个函数?如何调用一个函数?答:1)函数定义包括函数名称、形参以及函数体。
定义函数语法如下: Def functionname(list of parmeters)#Function body2)调用函数有两种方式。
当函数有返回值时将其当做一个值处理,如:larger = max( 3 , 4);当函数每天有返回值时,对函数的调用必须是一条语句,如:print(‘ Programming is fun’)6.3你能用传统的表达式简化程序清单6-1的max函数吗?答:return num1 if num1 > num2 else num26.4对none函数的调用总是它自己语句本身,但是对带有返回值函数的调用总是表达式的一部分。
这种说法正确吗?答:如果一个函数没有返回值,默认情况下,它返回一个特殊值none。
因此,无返回值函数不会返回值,它被称为none函数,none函数可以赋值给一个变量来表明这个变量不知想任何对象。
正确:调用一个函数void返回类型总是声明本身。
错误:调用一个有返回值的函数都是一个表达的一个组成部分。
6.5 none函数能不能有return语句?下面的return函数是否会造成语法错误?Def xFunction(x, y):Print (x + y)Return答:可以有return语句,会造成错误,因为这个函数是有返回值的函数。
6.6给出术语函数头、形参、实参的定义。
答:函数头:以一个def关键字开始,后面紧接着函数名以及形参并以冒号结束。
形参:函数头中的参数,它就像一个占位符。
实参:当调用函数时,就将一个值传递给形参,这个值就是实参。
6.8答:定义函数时未定义正确。
6.9答:None 函数无返回值6.10答:min函数应返回一个值。
Python语言程序设计(美-梁勇)第6章习题解答(英文)

Python语言程序设计(美-梁勇)第6章习题解答(英文)Python语言程序设计(第6章函数6.1使用函数的好处是什么?答:至少有三个好处:(1)重用代码(2)减少复杂性(3)易于维护6.2如何定义一个函数?如何调用一个函数?答:1)函数定义包括函数名称、形参以及函数体。
定义函数语法如下: Def functionname(list of parmeters)#Function body2)调用函数有两种方式。
当函数有返回值时将其当做一个值处理,如:larger = max( 3 , 4);当函数每天有返回值时,对函数的调用必须是一条语句,如:print(‘ Programming is fun’)6.3你能用传统的表达式简化程序清单6-1的max函数吗?答:return num1 if num1 > num2 else num26.4对none函数的调用总是它自己语句本身,但是对带有返回值函数的调用总是表达式的一部分。
这种说法正确吗?答:如果一个函数没有返回值,默认情况下,它返回一个特殊值none。
因此,无返回值函数不会返回值,它被称为none函数,none函数可以赋值给一个变量来表明这个变量不知想任何对象。
正确:调用一个函数void返回类型总是声明本身。
错误:调用一个有返回值的函数都是一个表达的一个组成部分。
6.5 none函数能不能有return语句?下面的return函数是否会造成语法错误?Def xFunction(x, y):Print (x + y)Return答:可以有return语句,会造成错误,因为这个函数是有返回值的函数。
6.6给出术语函数头、形参、实参的定义。
答:函数头:以一个def关键字开始,后面紧接着函数名以及形参并以冒号结束。
形参:函数头中的参数,它就像一个占位符。
实参:当调用函数时,就将一个值传递给形参,这个值就是实参。
6.8答:定义函数时未定义正确。
6.9答:None 函数无返回值6.10答:min函数应返回一个值。
Python程序设计第6章 习题解答

6.5 习题6.1 将一个列表的数据复制到另一个列表中。
程序分析:使用列表[:]。
程序源代码:a = [1, 2, 3]b = a[:]print(b)6.2 写代码,有如下列表,利用切片实现每一个功能。
li = [1, 3, 2, "a", 4, "b", 5,"c"]1)通过对li列表的切片形成新的列表l1,l1 = [1,3,2]2)通过对li列表的切片形成新的列表l2,l2 = ["a",4,"b"]3)通过对li列表的切片形成新的列表l3,l3 = ["1,2,4,5]4)通过对li列表的切片形成新的列表l4,l4 = [3,"a","b"]5)通过对li列表的切片形成新的列表l5,l5 = ["c"]6)通过对li列表的切片形成新的列表l6,l6 = ["b","a",3]l1=li[0:3]l2=li[3:6]l3=li[::2]l4=li[1:-2:2]l5=li[-1]print(l1,l2,l3,l4,l5)6.3 使用while和for循环分别打印字符串s="asdfer"中每个元素。
#while循环s="asdfer"count=0while count<len(s):print(s[count])count+=1#for循环for i in s:print(i)1216.4 利用for循环和range从100~10,倒序将所有的偶数添加到一个新列表中,然后对列表的元素进行筛选,将能被4整除的数留下来。
li = []for i in range(100,9,-1):if i%4==0:li.append(i)print(li)6.5 利用for循环和range,将1-30的数字一次添加到一个列表中,并循环这个列表,将能被3整除的数改成*。
第六章python面向对象-编程测试练习题及答案解析精选全文完整版

可编辑修改精选全文完整版第六章 python面向对象青少年编程知识练习题及答案解析一、单选题1、下列创建类,方法正确的是()A.Class food( ):B.Class Food():C.class Food()D.class Food():答案解析:D,创建类用class关键字,与类名中间隔一个空格,后面添加括号和冒号。
2、根据car()类创建实例对象,下列代码正确的是()A.Car=car()B.car=car()C.car=Car()D.Car=Car()答案解析:C,类名为大写Car(),对象名为小写的car。
3、在Car类中自定义speed方法,输出:行驶速度为60km/h,代码书写正确的是()A.B.C.D.答案解析:B,在类中定义方法,注意不要漏掉self和冒号。
4、以下代码创建了一个football对象:football=Ball(),调用football对象的play方法,下列选项正确的是()A.Football.play()B.football.Play()C.football.play()D.football.play答案解析:C,对象调用方法,对象名.方法名,不要忘记括号。
5、在Food类中创建eat方法,下列选项正确的是()A.Class Food():Def eat(self):B.class Food():def eat(self):C.class Food():def eat():D.class Food():def Eat(self)答案解析:B,创建类的关键字class,创建方法的关键字def。
6、以下代码创建了一个monkey对象:monkey=Animals(),调用monkey对象的name属性,下列选项正确的是()()D.monkey:name()答案解析:C,访问属性方法:对象名.属性名7、以传参的方式定义实例化方法时,参数之间用()符号进行分隔:A.分号;B.冒号:C.空格D.逗号,答案解析:D,参数属性之间用逗号分隔。
第六章 习题及练习答案

第六章习题及练习答案6.1填空题1. 打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄。
打开文件的四种基本模式有r (只读模式)、w只写模式、x(只写模式)、a(追加模式)等四种方式。
2.文件操作是通过软件将文件从硬盘读到内存,写入文件的操作也都是存入内存缓冲区buffer3. 调用write()、writeline()时,文件原有的内容会被清空,因为文件指针初始指向文件的首行首个字母,而进行写操作实质就是在文件指针指向的位置开始写入内容。
4.对文件进行操作必须需要的三个流程:第一,建立文件对象。
第二,调用文件方法进行操作。
第三,关闭文件。
6.2 简答题1.如何用Python删除一个文件答:使用os.remove(filename)或者os.unlink(filename);2.请指出下面编码错误,并答:答:>>>f = open("test.txt", mode="w")>>>f.write(u"python之路")错误有两个:读写文件时,要考虑字符编码问题;操作完文件要即时关闭文件描述符,同时还要注意代码的兼容性。
代码改正如下:>>> f = open("test.txt", mode="w")>>> content = u"Python之路">>> content = content.encode(encoding='utf-8')>>> f.write(content)>>> f.close()3.简单解释文本文件与二进制文件的区别。
答:(1)文本文件文本文件存储的是常规字符串,由若干文本行组成,通常每行以换行符'\n'结尾。
PYTHON核心编程第二版课后题答案第六章

def idcheck():'''6-2修改idcheck使之可以检测长度为一得标识符,并且可识别Python关键字'''import stringimport keywordkeys=keyword.kwlistalphas=string.letters+'_'nums=string.digitsalphanums=alphas+numsprint'Welcome to the Identifier Check V1.1'myInput=raw_input('identifier to test:')isOne=False#是否是一个字符if len(myInput)==1:isOne=Falseif myInput in keys:print'''invalid:symbol has been defined'''return Falseelif myInput[0]not in alphas:print'''invalid:first symbol must be alphabetic'''return Falseelif not isOne:otherInput=myInput[1:]for otherChar in otherInput:if otherChar not in alphanums:print'''invalid:remainn symbols must be alphanumeric'''return Falseprint"okay as an Identifier"return Truedef order(nlist):'''6-3(a)输入一串数字,从大到小排列注意:输入的是一个列表,其中的值为数字'''newlist=[]for x in nlist:newlist.append(int(x))return sorted(newlist,reverse=True)def order2(nlist):'''6-3(b)和a一样,不过要用字典序注意:字典序就是按字典的排列方式,比如21就大于111,因为2大于1方式就是把输入的数字变成字符串即可'''#将里面的元素统统变成字符串先newlist=[]for x in nlist:newlist.append(str(x))newlist=sorted(newlist,reverse=True)for i,x in enumerate(newlist):newlist[i]=int(x)return newlistdef avescore():'''输入测试得分,算出平均值'''scorelist=[]#分数列表while True:myinput=raw_input('Input the score(if No number quite):')try:scorelist.append(float(myinput))except:breakif not len(scorelist):return Falsereturn sum(scorelist)/len(scorelist)def showstr():'''6-5(a)更新2-7使之可以每次向前向后都显示一个字符串的一个字符'''istr=raw_input('Input string:')lens=len(istr)if lens==0:return Falseif lens==1:print istrreturn Truefor i,j in enumerate(istr):if i==0and len(istr)!=1:print j,istr[i+1]elif i==len(istr)-1and i!=0:print istr[i-1]else:print istr[i-1],j,istr[i+1]return Truedef mycmp():'''6-5(b)通过扫描判断两个字符串是否匹配,不能使用比较操作符或者cmp()''' str1=raw_input('First string:')str2=raw_input('Second string:')equal=len(str1)-len(str2)if not equal:return False#表示长度不相等#将字符串变成列表for i,j in enumerate(str1):if ord(j)-ord(str2[i]):#如果减下来不为0return Falsereturn Truedef isback():'''6-5(c)判断一个字符串是否是回文,忽略控制符号和空格[支持中文]'''import string#控制符表示ASCII码中0~31以及127这33个无法输出的字符denny=[chr(i)for i in xrange(0,32)]+list(string.whitespace)denny.append(chr(127))strs=raw_input('Please input string:')#将输入的数据解码成unicode因为在windows上默认是gbk,所以这里是gbk #如果是在其他命令行中,应该以命令行输入的字符编码为主strs=strs.decode('gbk')new=[]for i in strs:if i in denny:continuenew.append(i)lens=len(new)if lens%2:return Falseelse:half=lens/2if new[0:half]==new[-1:-half-1:-1]:return Truereturn Falsedef beback():'''6-5(d)输入一个字符串在后面重复一个反向拷贝,构成回文'''strs=raw_input('Input string:')#将输入的数据解码成unicode因为在windows上默认是gbk,所以这里是gbk #如果是在其他命令行中,应该以命令行输入的字符编码为主strs=strs.decode('gbk')#解码为unicodelens=len(strs)#这里之所以是-1:-lens-1:-1#分析如下:-1就是倒数第一个,-(lens+1)就是长度,-1是步进#就是说从倒数第一个开始-1(步进),一直减到倒数lens+1,由于切片里是[a:b]是a<=x<b的,#所以这里是lens+1而不是lensreturn strs+strs[-1:-lens-1:-1]def strip():'''6-6去掉输入的字符串的前面和后面的空格'''strs=raw_input('Input string:').decode('gbk')new=u''#由于只是去掉前面和后面的空格,所以不能遍历全部#分析,从前面遍历到非空格停止,从后面遍历到非空格位置#为了方便,我首先将字符串变成了列表strs=list(strs)lens=len(strs)for i in range(0,lens):#从前面开始遍历if strs[i]=='':strs[i]=''else:breakfor i in range(-1,-lens-1,-1):if strs[i]=='':strs[i]=''else:break#将list转成字符串nstrs=''for i in range(0,lens):nstrs+=strs[i]return nstrsdef num2eng():'''6-8输入一个整数,返回相应的英文,限定0~1000'''lists=['zero','one','two','three','four','five','six','seven','eight','nine']new=''while True:try:iput=int(raw_input('Please input a int(0~1000):'))if iput<0or iput>1000:continueexcept:continuebreakiput=str(iput)for j in iput:new+=lists[int(j)]+'-'return new[0:-1]def minute2time():'''6-9输入分钟,返回小时数和分钟'''minute=int(raw_input('Please input a minutes:'))hours=minute/60newminute=minute-hours*60return'%d:%02d'%(hours,newminute)def like():'''6-10写一个函数,返回一个跟输入字符串相似的字符串,要求字符串的大小写反转例如:Mr.Ed返回mR.eD'''import stringimport randomLetter=string.ascii_uppercase#大写字母字符串letter=string.ascii_lowercase#小写字母字符串name=raw_input('Input string:')newname=''for i in name:if i in Letter:newname+=random.choice(letter)continueif i in letter:newname+=random.choice(Letter)continuenewname+=ireturn newnamedef int2ip():'''6-11(a)创建一个整数到IP地址的转换'''ints=raw_input('Input Int:')#分析ip地址和整数的关系#ip地址是由4个字节组成,每个字节8位,换成16进制就是8位#FF.FF.FF.FF===>11111111111111111111111111111111#那么后面就是一个4位的二进制了#我们要做的就是将十进制的长整数换成4个字节的二进制或者4个16进制,然后再将每个字节转成独立的十进制#整数转成四个字节其实就是整数转16进制hexs=hex(int(ints))[2:]#hex转换后把最前面一个0x先去掉,然后在前面填0 while len(hexs)<8:hexs='0'+hexsip1=int(hexs[0]+hexs[1],16)ip2=int(hexs[2]+hexs[3],16)ip3=int(hexs[4]+hexs[5],16)ip4=int(hexs[6]+hexs[7],16)return'%03d.%03d.%03d.%03d'%(ip1,ip2,ip3,ip4)def ip2int():'''6-11(b)将ip地址转成整数'''ip=raw_input('Input Ip:')#分析:#首先将ip转成列表#然后变成十六进制,合并在一起#然后将十六进制转成十进制ips=ip.split('.')ip=[]for i in xrange(0,4):ip.append(int(ips[i]))ip[i]=hex(ip[i])[2:]if len(ip[i])==1:ip[i]='0'+ip[i]return int(ip[0]+ip[1]+ip[2]+ip[3],16)def findchr(string,char):'''6-12(a)在string中寻找char找到返回索引,找不到返回-1不能使用find或者index方法'''#strs=raw_input('Input string:')#char=raw_input('Input char:')#书中并没有说是找一个字符还是多个,我们假设为多个lens=len(char)#计算出char的长度#我们可以用in来指导是否存在if char not in string:return-1for i,j in enumerate(string):if j in char:#找到一个首字母哦~~~if string[i:i+lens]==char:#检查是否匹配return ireturn-1def rfindchr(string,char):'''6-12(b)和findchr类似,不过是从后面往前面找'''lens=len(char)lenstr=len(string)if char not in string:return-1rstring=string[::-1]#倒置的stringfor i,j in enumerate(rstring):if j in char:#索引比长度小1,所以lenstr-1#因为i是倒数的,所以整数就是#lenstr-1-iif string[lenstr-1-i:lenstr-1-i+lens]==char:return lenstr-1-ireturn-1def subchr(string,origchar,newchar):'''6-12(c)和findchr类似只不过找到匹配的字符就用新字符替换掉原来的字符并且返回修改后字符串'''#这里注意了,是要替换掉第一个,还是替换掉所有的呢?我这里默认是替换掉所有的lens=len(origchar)while True:index=string.find(origchar)if index>-1:#我的做法是将字符串分割开两段,然后中间加入新字符串string=string[0:index]+newchar+string[index+lens:]else:breakreturn stringdef atoc(string):'''6-13输入字符串返回复数,只能用complex不能用eval'''cindex=string.rfind('-')if cindex<=0:cindex=string.rfind('+')if cindex>0:real=float(string[0:cindex])compl=float(string[cindex:-1])return complex(real,compl)def rochambeau():'''6-14石头剪子布,输入一个行为,计算机随即产生一个对应的行为,并进行比较看谁赢'''import randomselect=['paper','shears','rock']#定个规则0>1>2cli=int(raw_input('Input your select[1.paper2.shears3.rock]:'))-1print'---You VS Computer---'print'\nYou[%s]'%select[cli],cup=random.choice([0,1,2])print'\tComputer[%s]\n'%select[cup]youwin='---You Win!!!---'cupwin='---Computer Win!!!---'eq='---Nobody Win---'if cup==cli:print eqreturnif(cup-cli)==-2or(cup>cli and(cli-cup!=-2)):print cupwinelse:print youwindef date2date():'''6-15计算两个日期间的天数'''#由于现在已经是2000年后了,所以我这里不用DD/MM/YY用DD/MM/YYYY日/月/年#这里用到了上面的isleapyear(year)函数import datetimemonth={1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}#默认的月份和天数while True:#这里做循环的目的是怕用户输入的日期不存在sdate=raw_input('Input Start Date[DD/MM/YYYY]:').split('/')dd,mm,yyyy=0,1,2sdate[dd],sdate[mm],sdate[yyyy]=int(sdate[0]),int(sdate[1]),int(sdate[2])if sdate[mm]>12or sdate[mm]<1:continueif isleapyear(sdate[yyyy]):month[2]=29if sdate[dd]<1or sdate[dd]>month[sdate[mm]]:continuebreak;while True:edate=raw_input('Input End Date[DD/MM/YYYY]:').split('/')edate[dd],edate[mm],edate[yyyy]=int(edate[0]),int(edate[1]),int(edate[2])if edate[mm]>12or edate[mm]<1:continueif isleapyear(sdate[yyyy]):month[2]=29if edate[dd]<1or edate[dd]>month[edate[mm]]:continuebreak;#挑简单的先解决,如果是同一天,返回0if sdate==edate:return0#如果是同年同月,直接相减if sdate[yyyy]==edate[yyyy]and sdate[mm]==edate[mm]:return edate[dd]-sdate[dd]#如果是同一年,那么就要判断当年是不是闰年if sdate[yyyy]==edate[yyyy]:#是闰年,则2月事29天if isleapyear(sdate[yyyy]):month[2]=29#然后开始计算月到月days=0for i in xrange(sdate[mm]+1,edate[mm]):#开始月到中止月之间的日期days+=month[i]#最后加上开始日当月过了几天+结束月当月过了几天days+=month[sdate[mm]]-sdate[dd]+edate[dd]return days#如果不是同一年,先计算年与年之间的日期days=0for year in xrange(sdate[yyyy]+1,edate[yyyy]):if isleapyear(year):days+=366else:days+=365#然后计算起始年到年终的日期if isleapyear(sdate[yyyy]):month[2]=29sdays=0for i in xrange(sdate[mm]+1,13):sdays+=month[i]sdays+=month[sdate[mm]]-sdate[dd]#最后计算终止年年头到结束日期if isleapyear(sdate[yyyy]):month[2]=29else:month[2]=28edays=0for i in xrange(1,edate[mm]):edays+=month[i]edays+=edate[dd]return edays+sdays+daysclass matrix:'''6-16矩阵东西比较多,我在这里做成了类来处理'''#我用一个列表来表示初始矩阵#这个矩阵式一个平面,包括纵向和横向#我这里用横向表示二级#例如#matrix=[[1,2,3],[2,3,4],[3,5,6]]转成矩阵就是这样##|123|#|234|#|356|#matrix=[]def__init__(self,matrix):self.matrix=matrixself.ylens=len(matrix)self.xlens=len(matrix[0])def ji(self,matrix2):'''6-16求两个矩阵的积'''import copyif len(matrix2)!=self.xlens:return Falseif len(matrix2[0])!=self.ylens:return Falsenew=copy.deepcopy(self.matrix)#这里主要是复制格式for i in xrange(0,self.ylens):for j in xrange(0,self.xlens):new[i][j]+=self.matrix[i][j]*matrix2[j][i]self.matrix=newreturn self.matrixdef add(self,matrix2):'''6-16求两个矩阵的和'''if len(matrix2)!=self.ylens:return Falseif len(matrix2[0])!=self.xlens:return Falsefor i in xrange(0,self.ylens):for j in xrange(0,self.xlens):self.matrix[i][j]+=matrix2[i][j]return self.matrixdef sub(self,matrix2):'''矩阵减法'''if len(matrix2)!=self.ylens:return Falseif len(matrix2[0])!=self.xlens:return Falsefor i in xrange(0,self.ylens):for j in xrange(0,self.xlens):self.matrix[i][j]-=matrix2[i][j]return self.matrixdef change(self):'''6-16转置矩阵'''#所谓转置就是将横和纵交换new_matrix=[]for i in xrange(0,self.xlens):new_matrix.append([])for j in xrange(0,self.ylens):new_matrix[i].append([])new_matrix[i][j]=self.matrix[j][i]self.matrix=new_matrixreturn self.matrixdef mypop(inlist):'''6-17功能类似pop'''del inlist[len(inlist)-1]return inlistdef showlist(inlist,row,xorder=True):'''6-19输入任意项序列,把它们等距离分列显示,由调用者提供数据和输出格式以及排序方式是水平还是垂直''' numl=len(inlist)*1./rowif numl.is_integer:numl=int(numl)else:numl=int(numl)+1outlist=[]x=0#建立一个list,用来格式化输出col,row=numl,rowfor i in xrange(0,col):outlist.append([])for j in xrange(0,row):outlist[i].append([])outlist[i][j]=inlist[x]x+=1if xorder:outlist[i]=sorted(outlist[i])line=[x for x in xrange(0,col)]if not xorder:#如果是垂直排序,处理一下for i in xrange(0,row):for j in xrange(0,col):line[j]=outlist[j][i]line=sorted(line)for x in xrange(0,col):outlist[x][i]=line[x]o=''for i in xrange(0,col):for j in xrange(0,row):if j==row-1:o='%d'%outlist[i][j]else:o='%d\t'%outlist[i][j]print o,if i!=col-1:print'\n'。
Python语言程序设计(美-梁勇)第6章习题解答(英文)

Chapter 6 Functions1.At least three benefits: (1) Reuse code; (2) Reduce complexity; (3) Easy to maintain.2. See the Sections 6.2 and 6.3 on how to declare and invoke functions.3. return num1 if (num1 > num2) else num24. True: a call to a function with a void return type is always a statement itself.False: a call to a value-returning function is always a component of an expression.5. A syntax error occurs if a return statement is not used to return a value in a value-returning function. You can have a return statement in a void function, whichsimply exits the function. So, this function is OK, although the return statement isnot needed at all.6. See Section 6.2.puting a sales commission given the sales amount and the commission ratedef getCommission(salesAmount, commissionRate):returns a valuePrinting a calendar for a monthdef printCalendar(month, year):Computing a square rootdef sqrt(value):returns a valueTesting whether a number is even and return true if it isdef isEven(value):returns a valuePrinting a message for a specified number of timesdef printMessage(message, times):Computing the monthly payment, given the loan amount,number of years, and annual interest rate.def monthlyPayment(loanAmount, numberOfYears,annualInterestRate):returns a valueFinding the corresponding uppercase letter given a lowercase letter.def getUpperCase(char letter):returns a value8.Line 2, 5-10: not indented correctly.9.None10.The min function should return a value.11.Using positional arguments requires the arguments be passed in the same order as their respective parameters in the function header. You can also call a function using keyword arguments, passing each argument in the form name=value.12.f(1, p2 = 3, p3 = 4, p4 = 4) # Correctf(1, p2 = 3, 4, p4 = 4) # Not Correctf(p1 = 1, p2 = 3, 4, p4 = 4) # Not Correctf(p1 = 1, p2 = 3, p3 = 4, p4 = 4) # Correctf(p4 = 1, p2 = 3, p3 = 4, p1 = 4) # Correct13. "Pass by value" is to pass a copy of the reference value to the function.14. Yes.15.(A) The output of the program is 0, because the variable max is not changed byinvoking the function max.(B)22 42 4 82 4 8 162 4 8 16 32(C)Before the call, variable times is 3n = 3Welcome to CS!n = 2Welcome to CS!n = 1Welcome to CS!After the call, variable times is 3(D)The code printsi is 11i is 22 1i is 3and then it is an infinite loop.16.17.(A) 23.424(B) 36518.x and y are not defined outside the function.19.Yes. The printout isy is 120.1 25 21 244 521.The parameter with non-default Argument must be defined before the parameter with default arguments.22.The later function definition will replace the previous function definition.23.Yes. The printout is14 4 45 1.824.random.randint(34, 55)25.chr(random.randint(ord('B'), ord('M')))26.5.5 + random.random() * 5027.chr(random.randint(ord('a'), ord('z')))。
浙大版《Python程序设计》题目集(第六章)

浙⼤版《Python程序设计》题⽬集(第六章)ls = eval(input())sum = 0for t in ls:sum = sum + tprint(sum)num = eval(input())count = 1students = []match = []cnt = 0while count <= num:stu = input().split(" ")students.append(stu)count = count + 1start = 0end = len(students) - 1while start < end:if students[start][0] != students[end][0]:match.append(students[start][1])match.append(students[end][1])students.pop(end)start = start + 1end = len(students) - 1else:end = end - 1for t in match:cnt = cnt + 1if cnt % 2 == 0:print(t)else:print(t,end = ' ')strs = input()strs = strs.replace("["," ")strs = strs.replace("]"," ")strs = strs.replace("("," ")strs = strs.replace(")"," ")strs = strs.replace(","," ")s = ''flag = 0sum = 0for str in strs:if str == '"':flag = flag + 1if flag % 2 == 0 and str != '"':s = s + strprint(s)s = s.split()for t in s:sum = sum + int(t)print(sum)#采⽤递归思想实现def deep_sum(ls,deep):sum = 0for i in ls:if isinstance(i,int):sum = sum + i * deepelif isinstance(i,list):sum = sum + deep_sum(i,deep + 1)return sumls = eval(input())print(deep_sum(ls,1))def count_list(ls,deep):count = 0for i in ls:if not isinstance(i,list):count = count + 1 * deepelif isinstance(i, list):count = count + count_list(i,deep + 1)return countls = eval(input())print(count_list(ls,1))def count_num(ls,deep):count = 1num = 0for i in ls:if isinstance(i,list):count = count + 1if count == deep:num = num + len(i)breakelse:num = num + count_num(i,deep - 1)else:if count == deep:num = num + len(ls)breakreturn numls = eval(input())deep = eval(input())print(count_num(ls,deep))num = eval(input())count = 1ls = []sum_max = 0index = 0while count <= num:info = input().split(" ")ls.append(info)count = count + 1sum_max = sum_max + int(ls[0][2]) + int(ls[0][3]) + int(ls[0][4]) for i in range(1,len(ls)):if int(ls[i][2]) + int(ls[i][3]) + int(ls[i][4]) > sum_max:sum_max = int(ls[i][2]) + int(ls[i][3]) + int(ls[i][4])index = iprint(ls[index][1],ls[index][0],sum_max,end = '')def all_sort(i,s = ""):s = s + iif len(s) < num:for j in strs:if j not in s:all_sort(j,s)else:print(s)num = eval(input())strs = [str(i + 1) for i in range(num)]for i in strs:all_sort(i)。
《python核心编程第二版》课后习题6-12答案

《python核⼼编程第⼆版》课后习题6-12答案 下午脑⼦⽡特,想了半天也没有想出算法,刚刚抽风终于实现了,特此记录。
 ̄□ ̄||题⽬(a)创建⼀个名字为 findchr()的函数,findchr()要在字符串 string 中查找字符 char,找到就返回该值的索引,否则返回-1.(b)创建另⼀个叫 rfindchr()的函数,查找字符 char 最后⼀次出现的位置.它跟 findchr()⼯作类似,不过它是从字符串的最后开始向前查找的.(c)创建第三个函数,名字叫 subchr(),subchr()跟 findchr()类似,不同的是,如果找到匹配的字符就⽤新的字符替换原先字符.返回修改后的字符串.注意:以上均不能使⽤string.*find()或者 string.*index()函数和⽅法def findchr(string, char):if char in string:i=0while string[i:i+len(char)]!=char:i+=1else:return ielse:return -1def rfindchr(string, char):if char in string:i=0while i<(len(string)-len(char)+1):if string[i:i+len(char)]!=char:i+=1else:s=ii+=1else:return selse:return -1def subchr(string, origchar, newchar):if origchar in string:i=0while string[i:i+len(origchar)]!=origchar:i+=1else:new_string=string[:i]+newchar+string[(i+len(origchar)):]return new_stringelse:return -1#运⾏结果print(findchr('xabcxxxx', 'abc'))print(rfindchr('abcxxxxabc', 'abc'))print(subchr('abcxxxx', 'abc','lilip'))17lilipxxxx。
python核心编程答案.pdf

python核心编程答案.pdfpython核心练习(第二章)2-3a=int(input('A='))b=int(input('B='))print('A-B=%d,A+B=%d\nA/B=%d,A**B=%d,A%%B=%d' % (a-b ,a+b ,a/b,a**b,a%b))2-4(a)print(input('Enter a string:'))(b)print(int(input('Enter a value:')))2-5(a)i=0while i<11:print(i)i+=1(b)for i in range(11): print(i) 2-6v=int(input('Enter a number to determine positive or negative:')) if v<0:print('%d is negative' % v)elif v==0:print('you enter zero')else:print('%d is positive' % v)2-7while 循环s=input('Enter a string:') i=0while i<len(s):< p="">print(s[i])i+=1for 循环s=input('Enter a string:') for i in s: print(i)2-8while 循环print('Enter five number') v=[]i=0s=0while i<5 :a=input('n%d=' % (i+1))v.extend([int(a)])s=s+v[i]i+=1print(v)print('sum=%d' % s)print('Enter five number')v=[]s=0for i in range(5):a=input('n%d=' % (i+1))v.extend([int(a)])s=s+v[i]print(v)print('sum=%d' % s)2--9print('Enter five number')v=[]s=0for i in range(5):a=input('n%d=' % (i+1))v.extend([int(a)])s=s+v[i]print('ave=%f' % (float(s)/len(v))) 2-10i=1n=int(input('Enter a number between 1-100:')) if n<=100 and n>=1:print('Done')i=0else:print('Error')2-11while True:s=0c=int(input("'1'sum,'2'ave,'0'exit:\n"))if c==1:for i in range(5):n=int(input('n%d=' % (i+1)))s+=nprint(s)if c==2:for i in range(5):n=int(input('n%d=' % (i+1)))s+=nprint(float(s/5))if c==0:break2-15a=int(input('a='))b=int(input('b='))c=int(input('c='))n=[]a,b=b,aif a>c:a,c=c,aif b>c:b,c=c,bn.extend([a,b,c])print(n)python核心练习(第三章)import osls=os.linesepdef write():while True:fname=input('Enter file name:')if os.path.exists(fname):print('Error %s already exists ' % fname) else: breakall=[]print("\nEnter lines ('.' by itself to quit).\n") while True:entry=input('>')if entry=='.':breakelse:all.append(entry)fobj=open(fname,'w')fobj.writelines(['%s%s' % (x,ls) for x in all]) fobj.close()print('Done')def read():while True:fname=input('Enter filename:')if not os.path.exists(fname):print('sorry,%s is not exists' % fname) else:breaktry:fobj=open(fname,'r')except IOError as e:print("*** file open error" ,e)else:for eachline in fobj:print (eachline),fobj.close()i=0while i!='q':i=input("'r'read,'w',write,'q'quite:")if i=='r':read()elif i=='w':write()python核心练习(第四、五章)4-1python对象的三个属性,身份,类型,值(ID,type,value)除了值之外其他两个都是只读的如果对象支持更新操作,那么他的值就是可改变的,否也是只读的5-2def mul(a,b):m=a*breturn(m)x=int(input('x='))y=int(input('y='))print(mul(x,y))5-3def grade(a):if a>100 or a<0:print("error,please,input your score between 1 to 100") elif a>=90:print("A")elif a>=80:print("B")elif a>=70:print("C")elif a>=60:print("D")else:print("F")while True:x=int(input("Enter your score:"))if x==0:breakelse:grade(x)5-4def ly(y):if (y%100!=0 and y%4==0) or y%400==0: print('%d is leap year' % y)else:print('%d is not leap year' % y)while True:x=int(input('Enter the year:'))if x==0:breakelse:ly(x)5-5def cd(m0):if m0<0 or m0>1:print('Error,请输入0到1之间的金额')else:m=m0*100a=m/25a1=m%25b=a1/10b1=a1%10c=b1/5c1=b1%5d=c1print('%f美元=25美分x%d+10美分x%d+5美分x%d+1美分x%d' % (m0,a,b,c,d))while True:m0=float(input('请输入金额:'))if m0==0:breakelse:cd(m0)5-6while True:s=input('请输入要计算的式子:\n')if s==0:breakelse:if s.find('*')!=-1:ls=s.split('*')print(float(ls[0])*float(ls[1])) elif s.find('+')!=-1:ls=s.split('+')print(float(ls[0])+float(ls[1])) elif s.find("^")!=-1:ls=s.split("^")print(float(ls[0])**float(ls[1])) elif s.find('/')!=-1:ls=s.split('/')print(float(ls[0])/float(ls[1])) elif s.find('%')!=-1:ls=s.split('%')print(float(ls[0])%float(ls[1])) 5-8import mathdef sqcu():a=float(input('输入正方形或立方体的边长:'))print('边长为',a,'的正方形面积是',round(a*a,3))print('边长为',a,'立方体体积是',a**3)def cisp():r=float(input('输入圆或球的半径:'))print('半径为',r,'的圆面积是',round(math.pi*(r**2),3))print('半径为',r,'的球的体积是',round(math.pi*(r**3)*4/3,3)) sqcu()cisp()5-10def FtoC():f=float(input('输入华氏温度:'))c=(f-32)*(5/9)print(f,'华氏度等于',round(c,3),'摄氏温度')FtoC()5-11def evod():e=[]o=[]for i in range(21):if i%2==0:e.append(i)else:o.append(i)print('偶数:',e,'\n奇数:',o)def judiv():a,b=int(input('enter the first number:')),int(input('enter the second number:')) if a%b==0:print(a,'能被',b,'整除')else:print(a,'不能被',b,'整除')evod()judiv()5-13def hmtom():hm=input("输入时间(格式'hh:mm'):")lhm=hm.split(':')m=float(lhm[0])*60+float(lhm[1])print(m)hmtom()5-15def gcd():a,b=int(input('a=')),int(input('b='))t1,t2=a,bwhile b!=0:if a<b:< p="">a,b=b,aelse:a,b=b,a%bprint('最大公约数是%d,最小公倍数是%d' % (a,t1*t2/a)) gcd() 5-16def payment():s=float(input('Enter opening balance:'))p=float(input('Enter monthly payment:'))print("Pymt# Paid Remaining Balance")print("------- ------- -----------")n=0print(n," ",p," ",round(s,2))while s>=p:s=s-pn=n+1print(n," ",p," ",round(s,2))print(n," ",round(s,2)," ",p)while True:payment()5-17import randoml=[]i=0N=random.randint(2,100) while i<="" p="">n=random.randint(0,2**31)l.append(n)i+=1print(l)print('\n')for x in range(len(l)):for y in range(x,len(l)): if l[x]<l[y]:< p="">l[y],l[x]=l[x],l[y] print(l) </l[y]:<></b:<></len(s):<>。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
if otherChar not in alphanums:
print '''invalid:remainn symbols must be alphanumeric'''
if iput <0 or iput >1000:
continue
except:
continue
break
iput = str(iput)
for j in iput:
if lens%2:return False
else:
half = lens/2
if new[0:half] == new[-1:-half-1:-1]:return True
return False
def beback():
denny = [chr(i) for i in xrange(0,32)]+list(string.whitespace)
denny.append(chr(127))
strs = raw_input('Please input string:')
# 将输入的数据解码成unicode 因为在windows上默认是gbk,所以这里是gbk
hours = minute/60
newminute = minute-hours*60
return '%d:%02d' % (hours,newminute)
def like():
'''6-10 写一个函数,返回一个跟输入字符串相似的字符串,要求字符串的大小写反转
# 所以这里是 lens+1 而不是 lens
return strs+strs[-1:-lens-1:-1]
def strip():
'''6-6 去掉输入的字符串的前面和后面的空格'''
strs = raw_input('Input string: ').decode('gbk')
'''
newlist = []
for x in nlist:
newlist.append(int(x))
return sorted(newlist,reverse=True)
def order2(nlist):
'''6-3(b) 和a一样,不过要用字典序
'''6-5(d) 输入一个字符串在后面重复一个反向拷贝,构成回文'''
strs = raw_input('Input string: ')
# 将输入的数据解码成unicode 因为在windows上默认是gbk,所以这里是gbk
# 如果是在其他命令行中,应该以命令行输入的字符编码为主
lists = ['zero','one','two','three','four','five','six','seven','eight','nine']
new =''
while True:
try:
iput = int(raw_input('Please input a int(0~1000): '))
newlist = sorted(newlist,reverse=True)
for i,x in enumerate(newlist):
newlist[i] = int(x)
return newlist
def avescore():
'''输入测试得分,算出平均值'''
new = u''
# 由于只是去掉前面和后面的空格,所以不能遍历全部
# 分析,从前面遍历到非空格停止,从后面遍历到非空格位置
# 为了方便,我首先将字符串变成了列表
strs = list(strs)
lens = len(strs)
for i in range(0,lens): # 从前面开始遍历
注意:字典序就是按字典的排列方式,比如 21 就大于 111 ,因为 2大于1
方式就是把输入的数字变成字符串即可
'''
# 将里面的元素统统变成字符串先
newlist = []
for x in nlist:
newlist.append(str(x))
istr = raw_input('Input string: ')
lens = len(istr)
if lens==0:return False
if lens==1:
print istr
return True
for i,j in enumerate(istr):
new += lists[int(j)]+'-'
return new[0:-1]
def minute2time():
'''6-9 输入分钟,返回小时数和分钟'''
minute = int(raw_input('Please input a minutes: '))
return False
return True
def isback():
'''6-5(c)判断一个字符串是否是回文,忽略控制符号和空格[支持中文]'''
import string
# 控制符表示 ASCII 码中 0~31 以及127 这33个无法输出的字符
scorelist = [] # 分数列表
while True:
myinput = raw_input('Input the score(if No number quite): ')
try:
scorelist.append(float(myinput))
strs = strs.decode('gbk') # 解码为 unicode
lens = len(strs)
# 这里之所以是 -1:-lens-1:-1
# 分析如下: -1就是倒数第一个,-(lens+1) 就是长度,-1是步进
# 就是说从倒数第一个开始-1(步进),一直减到倒数 lens+1,由于切片里是 [a:b] 是 a<=x<b的,
if strs[i] == ' ':strs[i] =''
else:break
for i in range(-1,-lens-1,-1):
if strs[i] == ' ':strs[i] = ''
else:break
if i ==0 and len(istr)!=1:
print j,istr[i+1]
elif i == len(istr)-1 and i != 0:
print istr[-1]
else:
print istr[i-1],j,istr[i+1]
equal = len(str1) - len(str2)
if not equal:return False # 表示长度不相等
# 将字符串变成列表
for i,j in enumerate(str1):
if ord(j)-ord(str2[i]):#如果减下来不为0
nums = string.digits
alphanums = alphas+nums
print 'Welcome to the Identifier Check V1.1'
myInput = raw_input('identifier to test: ')
def idcheck():
'''6-2 修改idcheck使之可以检测长度为一得标识符,并且可识别
Python 关键字
'''
import string
import keyword
keys = keyword.kwlist
alphas = string.letters+'_'
isOne = False # 是否是一个字符
if len(myInput) == 1:isOne = False
if myInput in keys:
print '''invalid:symbol has been defined'''
return False
elif myInput[0] not in alphas:
print '''invalid:first symbol must be alphabetic'''
return False
elif not isOne:
otherInput = myInput[1:]