《Python程序设计基础》习题答案与分析 下载本文

内容发布更新时间 : 2024/4/28 8:11:44星期一 下面是文章的全部内容请认真阅读。

5<=x<10 10<=x<20 20<=x 3x-5 0.5x-2 0 答: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 = \x = x.replace('i ','I ') x = x.replace(' i ',' I ') print(x)

2)使用正则表达式

x = \import re

pattern = re.compile(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:

break print(x)

4.2 假设有一段英文,其中有单词中间的字母“i”误写为“I”,请编写程序进行纠正。 答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可。

import re

x = \print(x)

pattern = re.compile(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:

break print(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 re

x = 'This is a a desk.'

pattern = re.compile(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 = re.compile(r'(?P\\b\\w+\\b)\\s(?P=f)') matchResult = pattern.search(x)

x = x.replace(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) False

4.5 编写程序,用户输入一段英文,然后输出这段英文中所有长度为3个字母的单词。 答:这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可。

import re

x = input('Please input a string:')

pattern = re.compile(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 math def 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 =0 for i in v:

if 'A'<=i<='Z': capital+=1 elif 'a'<=i<='z': little+=1 elif '0'<=i<='9': digit+=1 else:

other+=1

return (capital,little,digit,other) x = 'capital = little = digit = other =0'