《Python程序设计(第3版)》[美] 约翰·策勒(John Zelle) 第 3 章 答案

判断对错

1.由计算机存储和操作的信息称为数据。
2.由于浮点数是非常准确的,所以通常应该使用它们,而不是int。
3.像加法和减法这样的操作在mAth库中定义。
4.n 项的可能排列的数目等于 n!。
5.sqrt函数计算数字的喷射(squirt)。
6.floAt数据类型与实数的数学概念相同。
7.计算机使用二进制表示数字。
8.硬件floAt可以表示比硬件int更大范围的值。
9.在获取数字作为用户输入时,类型转换函数(如floAt)是evAl的安全替代。
10.在 Python 中,4 + 5 产生与 4.0 + 5.0 相同的结果类型。
解答

 1 T
 2 F(p.36 “由于浮点值不精确,而 int 总是精确的,所以一般的经验 法则应该是:如果不需要小数值,就用 int”)
 3 F(见 p.37 “表 3.1 Python 内置的数值操作”)
 4 T
 5 F(p.41 “该程序使用了 mAth 库模块的平方根函数 sqrt”)
 6 F(p.36 “int 和 floAt 之间的另一个区别是,floAt 类型只能表示对实数的近似”)
 7 T
 8 T
 9 T
10 F(p.38 “结果的数据类型取决于操作数的类型”)

多项选择
1.下列________________项不是内置的 Python 数据类型。
A.int
B.float
C.rational
D.string
2.以下________________项不是内置操作。
A.+
B.%
C.abs()
D.sqrt()
3.为了使用 math 库中的函数,程序必须包括________________。
A.注释
B .循环
C.操作符
D .import 语句
4.4!的值是________________。
A.9
B.24
C.41
D.120
5.用于存储π的值,合适的数据类型是________________。
A.int
B.float
C.irrational
D.string
6.可以使用 5 位比特表示的不同值的数量是________________。
A.5
B.10
C.32
D.50
7.在包含 int 和 float 的混合类型表达式中,Python 会进行的转换是________________。
A.浮点数到整数
B.整数到字符串
C.浮点数和整数到字符串
D.整数到浮点数
8.下列________________项不是 Python 类型转换函数。
A.float
B.round
C.int
D.abs
9.用于计算阶乘的模式是________________。
A.累积器
B.输入、处理、输出
C.计数循环
D.格子
10. ________________。
A.导致溢出
B.转换为 float
C.打破计算机
D.使用更多的内存
解答

 1 C(Python 使用 fractions 库中的 Fraction 函数来表示有理数,其实就是用分数来表示有理数🙂)
 2 D(sqrt() 函数是 math 库中的函数)
 3 D
 4 B(4!= 4 × 3 × 2 × 1 = 24 5 B
 6 C(1 位比特可以表示两个不同的值,5 位比特可以表示 2^5 = 32 个不同的值)
 7 D(p.38 “在“混合类型表达式”中,Python 会自动将int 转换为浮点数,并执行浮点运算以产生浮点数结果。”)
 8 D(abs() 函数返回实数的绝对值或负数的模)
 9 A
10 D

讨论

1.显示每个表达式求值的结果。确保该值以正确的形式表示其类型(int 或float)。如果表达式是非法的,请解释为什么。

a. 7.4
b. 5.0
c. 8
d. 表达式非法(p.42 “sqrt 函数无法计算负数的平方根。Python 打印“math domain error”。这告诉我们,负数不在sqrt 函数的定义域中”。若要计算负数的平方根,请使用 cmath.sqrt )
e. 11
f. 27(3 ** 3 相当于 pow(3, 3),见 pow 。注意与 math.pow 的不同之处)

2.将以下每个数学表达式转换为等效的Python 表达式。你可以假定math 库已导入(通过import math)。
第 3 章 讨论 2

a. (3 + 4) * 5
b. n * (n - 1) / 2
c. 4 * math.pi * r ** 2
d. math.sqrt(r * (math.cos(a)) ** 2 + r * (math.sin(b)) ** 2)
e. (y2 - y1) / (x2 - x1)

3.显示将由以下每个 range 表达式生成的数字序列。

a.range(5)
b.range(3, 10)
c.range(4, 13, 3)
d.range(15, 5, -2)
e.range(5, 3)
Tips: range 类型表示一个不可变的数字序列,在 range(start, stop[, step]) 中,如果省略了 step 参数,则其默认为 1;如果省略 start 参数,则其默认为 0;如果 step 参数为 0,则会引发 ValueError
a. [0, 1, 2, 3, 4]
b. [3, 4, 5, 6, 7, 8, 9]
c. [3, 6, 9, 12]
d. [15, 13, 11, 9, 7]
e. [](省略了 step 参数,且 start 小于 stop,生成一个空的数字序列)

4.显示以下每个程序片段产生的输出。
在这里插入图片描述

a. 1
   4
   9
   16
   25
   36
   49
   64
   81
   100
b. 1 : 1
   3 : 27
   5 : 125
   7 : 343
   9 : 729
   9
c. 012
   212
   412
   612
   812
   done
d. 1
   2
   3
   4
   5
   6
   7
   8
   9
   10
   385

5.如果使用负数作为 round 函数中的第二个参数,你认为会发生什么?例如,round(314.159265, -1) 的结果应该是什么?请解释答案的理由。在你写下答案后,请参阅 Python 文档或尝试一些例子,看看Python 在这种情况下实际上做了什么。

310.0(参阅 round() 函数)
 1 n = 314.159265
 2 s = str(n)
 3 l = s.split('.')
 4 for i in range(-len(l[0]), len(l[1]) + 1):
 5     print('round({0}, {1}) = {2}'.format(n, i, round(n, i)))
 6 # Output:
 7 # round(314.159265, -3) = 0.0
 8 # round(314.159265, -2) = 300.0
 9 # round(314.159265, -1) = 310.0
10 # round(314.159265, 0) = 314.0
11 # round(314.159265, 1) = 314.2    ①
12 # round(314.159265, 2) = 314.16
13 # round(314.159265, 3) = 314.159
14 # round(314.159265, 4) = 314.1593
15 # round(314.159265, 5) = 314.15927    ③
16 # round(314.159265, 6) = 314.159265
17 
18 for i in range(-2, 3):
19     print('round(0.5, {0}) = {1}'.format(i, round(0.5, i)))
20 # Output:
21 # round(0.5, -2) = 0.0
22 # round(0.5, -1) = 0.0
23 # round(0.5, 0) = 0.0    ②
24 # round(0.5, 1) = 0.5
25 # round(0.5, 2) = 0.5
Tips: 根据 Python 3.5 的文档,round() 函数并不是简单地四舍五入取整,“For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2”,即如果值距离两边的整数的距离相等,则向相邻的偶数取整(具体见结论 6)。.
结论:

round 函数用于对浮点数进行四舍五入求值,具体保留几位小数,由传入的 ndigits 参数来控制
ndigits 是可选参数,当不传入时,即以默认保留 0 位小数进行取整,返回的是整数
ndigits 传入 0 时,与不传入时一样以保留 0 位小数进行取整,但返回的是浮点数
ndigits 传入正数时,取整到 ndigits 位小数,整数部分不变,返回的是浮点数。如果传入的浮点数的小数部分的位数小于 ndigits 位,则返回原来的数
ndigits 传入负数时,对整数部分的后 abs(ndigits) 位进行取整( 例如:ndigits 为 -3,则对整数部分的后 3 位进行取整),小数部分清 0,返回的是浮点数。如果 ndigits 的绝对值大于传入的浮点数的整数部分的位数,则返回 0.0
当值距离两边的整数的距离相等时的取整方法,根据官方文档,Python 2.x 与 Python 3.x 的具体实现是不同的,这里只讨论 Python 3.x 的情况。这里需要提到一种取整方法,Banker’s rounding 算法(银行家舍入法)。简单地说就是,如果舍弃部分左边的数字为奇数,则向上取整(如 ①);如果舍弃部分左边的数字为偶数,则向下取整(如 ②)(参考链接)
(浮点运算的一个问题)查看 ③ 的结果,按照上面的规则,round(314.159265, 5) 应该等于 314.15926 才对,可是答案却不符合我们的预期。这不是一个 Bug,这跟浮点数的精度有关。在计算机中浮点数不一定能精确表达,导致在计算机中保存的 314.15926 比其真实值要大一点点,因此取整时就近似为了 314.15927(参考链接)

6.当整数除法或余数运算的操作数为负数时,你认为会发生什么?考虑以下每种情况并尝试预测结果。然后在 Python 中试试。(提示:回顾一下神奇的公式 a = (a // b)(b) + (a % b)。)

a.−10 // 3
b.−10 % 3
c.10 // −3
d.10 % −3
e.−10 // −3
>>> -10 // 3
-4
>>> -10 % 3
2
>>> 10 // -3
-4
>>> 10 % -3
-2
>>> -10 // -3
3
1、首先要知道一点,取余结果的符号与 % 第二操作数的符号相同,且 0 <= abs(a % b) < abs(b)。a % b 实质上是 a 加上或者减去整数个 b,使得结果落在区间 [0, b - 1](b > 0) 或 [b + 1, 0](b < 0),那么得到的结果就是 a % b
2、先求 b. ,在表达式 -10 % 3 中,3 大于 0,所以结果的范围是 [0, 2],由 -10 + 4 * (3) = 2 得 -10 % 3 = 2;再求 a. ,根据神奇的公式 a = (a // b)(b) + (a % b),可以得出 -10 // 3 = -4
3、先求 d. ,在表达式 10 % -3 中,-3 小于 0,所以结果的范围是 [-2, 0],由 10 + 4 * (-3) = -2 得 10 % -3 = -2;再求 c. ,可得 10 // -3 = -4
4、对于 e. 也是一样,代入神奇的公式 a = (a // b)(b) + (a % b) 有 -10 = (-10 // -3)(-3) + (-10 % -3),由于 (-10 % -3) 的值为负且在区间 [-2, 0] 内,-10 // -3 只能为 3

编程练习
1.编写一个程序,利用球体的半径作为输入,计算体积和表面积。以下是一些可能有用的公式:

 1 #    A program to calculate the volume and 
 2 #     surface area of a sphere from its radius, given as input
 3 import math
 4 def main():
 5     radius = float(input("radius: "))
 6     volume = 4 / 3 * math.pi * radius ** 3
 7     area = 4 * math.pi * radius ** 2
 8     print("volume: {0}\nsurface area: {1}".format(volume, area))
 9 
10 main()

2.给定圆形比萨饼的直径和价格,编写一个程序,计算每平方英寸的成本。面积公式为

 1 #   A program to calculate the cost per square inch of 
 2 #   a circular pizze, given its diameter and price
 3 import math
 4 def main():
 5     diameter = float(input("diameter(in inches): "))
 6     price = float(input("price (in cents): "))
 7     area = math.pi * (diameter / 2) ** 2
 8     cost = price / area
 9     print("The cost is", cost, "cents per square inch.")
10 
11 main()

3.编写一个程序,该程序基于分子中的氢、碳和氧原子的数量计算碳水化合物的分子量(以克/摩尔计)。程序应提示用户输入氢原子的数量、碳原子的数量和氧原子的数量。然后程序基于这些单独的原子量打印所有原子的总组合分子量。

例如,水(H2O)的分子量为2(1.00794)+ 15.9994 = 18.01528。

 1 #   A program to compute the molecular weight of a hydrocarbon
 2 import math
 3 def main():
 4     hydrogen_atoms = float(input("Please enter the number of hydrogen atomes: "))
 5     carbon_atoms = float(input("Please enter the number of carbon atomes: "))
 6     oxygen_atoms = float(input("Please enter the number of oxygen atomes: "))
 7     
 8     molar_mass = dict({"H": 1.00794, "C": 12.0107, "O": 15.9994})
 9     molecular_weight = hydrogen_atoms * molar_mass["H"] + carbon_atoms * molar_mass["C"] \
10     + oxygen_atoms * molar_mass["O"]
11     print("The molecular weight of all the atoms is",   molecular_weight)
12 
13 main()

4.编写一个程序,根据闪光和雷声之间的时间差来确定雷击的距离。声速约为1100 英尺/秒,1 英里为 5280 英尺。

1 #   A program to calculate the distance to a lightning strike 
2 def main():
3     seconds = float(input("Enter number of seconds between flash and crash: "))
4     feet = 1100 * seconds
5     miles = feet / 5280.0
6     print("The lightning is approximately", miles, "miles away.")
7 
8 main()

5.Konditorei 咖啡店售卖咖啡,每磅 10.50 美元加上运费。每份订单的运费为每磅 0.86 美元 + 固定成本 1.50 美元。编写计算订单费用的程序。

 1 #   A program that calculates the cost of an order
 2 def main():
 3     account = float(input("How many pounds of coffee do you want? "))
 4     coffee_cost = pounds * 10.5
 5     shipping = pounds * 0.86 + 1.50
 6     print("Cost of coffee:", coffee_cost)
 7     print("Shipping:      ", shipping)
 8     print("-------------------------------")
 9     print("Total due:     ", coffee_cost + shipping)
10 
11 main()

6.使用坐标(x1,y1)和(x2,y2)指定平面中的两个点。编写一个程序,计算通过用户输入的两个(非垂直)点的直线的斜率。

 1 #   A program to calculate the slope of a line through
 2 #   two (non-vertical) points entered by the user
 3 def main():
 4     x1 = float(input("Enter the x for the first point: "))
 5     y1 = float(input("Enter the y for the first point: "))
 6     x2 = float(input("Enter the x for the second point: "))
 7     y2 = float(input("Enter the y for the second point: "))
 8     slope = (y2 - y1) / (x2 - x1)
 9     print("The slope of the line is", slope)
10     
11 main()

7.编写一个程序,接受两点(见上一个问题),并确定它们之间的距离。

 1 #   A program to calculate the distance between
 2 #   two points entered by the user
 3 import math
 4 def main():
 5     x1 = float(input("Enter the x for the first point: "))
 6     y1 = float(input("Enter the y for the first point: "))
 7     x2 = float(input("Enter the x for the second point: "))
 8     y2 = float(input("Enter the y for the second point: "))
 9     distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
10     print("The distance between the points is", distance)
11 
12 main()

8.格里高利闰余是从 1 月1 日到前一个新月的天数。此值用于确定复活节的日期。它由下列公式计算(使用整型算术):

C=year//100
epact=(8+(C//4)−C+((8C+13)//25)+11(year%19))%30

编写程序,提示用户输入4 位数年份,然后输出闰余的值。

1 #   A program to figure out the Gregorian epact value of year
2 import math
3 def main():
4     year = int(input("Enter the year (e.g. 2020): "))
5     C = year // 100
6     epact = (8 + (C//4) - C + ((8 * C + 13) // 25) + 11 * (year % 19)) % 30
7     print("The epact value is", epact, "days.")
8 
9 main()
关于如何确定复活节的日期的参考链接:
http://www.madore.org/~david/misc/calendar.html)
https://www.dateofeaster.com/

9.使用以下公式编写程序以计算三角形的面积,其三边的长度为 a、b 和 c:

 1 #   A program to calcualte the area of a triangle given 
 2 #   the length of its three sides--a, b, and c
 3 import math
 4 def main():
 5     a= float(input("Please enter the length of side a: "))
 6     b= float(input("Please enter the length of side b: "))
 7     c= float(input("Please enter the length of side c: "))
 8     s = (a + b + c) / 2
 9     A = math.sqrt(s * (s - a) * (s - b) * (s - c))
10     print("The area of the triangle is", A)
11     
12 main()

10.编写程序,确定梯子斜靠在房子上时,达到给定高度所需的长度。梯子的高度和角度作为输入。计算长度使用公式为:

注意:角度必须以弧度表示。提示输入以度为单位的角度,并使用以下公式进行转换:

 1 #   A program to determine the length of a ladder required 
 2 #   to reach a given height when leaned against a house
 3 import math
 4 def main():
 5     height = float(input("height: "))
 6     degrees = float(input("angle(in degrees): "))
 7     radians = math.pi / 180 * angle
 8     length = height / math.sin(radians)
 9     print("length:", length)
10     
11 main()
angle 是梯子与地面的夹角

11.编程计算前 n 个自然数的和,其中 n 的值由用户提供。

 1 #   A program to find the sum of the first n natural numbers
 2 def main():
 3     n = int(input("Please enter the value of n: "))
 4     s = 0
 5     for i in range(1, n + 1):
 6         s += i
 7     # s = n * (n + 1) // 2
 8     print("The sum from i to", n, "is", s)
 9 
10 main()

12.编程计算前 n 个自然数的立方和,其中 n 的值由用户提供。

 1 #   A program to find the sum of the cubes of the first n natural numbers
 2 def main():
 3     n = int(input("Please enter the value of n: "))
 4     s = 0
 5     for i in range(1, n + 1):
 6         s += i ** 3
 7     # s = (n * (n + 1) // 2) ** 2
 8     print("The sum of cubes of 1 through", n, "is", s)
 9 
10 main()

13.编程对用户输入的一系列数字求和。 程序应该首先提示用户有多少数字要求和,然后依次提示用户输入每个数字,并在输入所有数字后打印出总和。(提示:在循环体中使用输入语句。)

 1 #   A program to sum a series of numbers entered by the user
 2 def main():
 3     n = int(input("How many numbers are to be summed? "))
 4     s = 0
 5     for i in range(1, n + 1):
 6         each = float(input("Please enter a number: "))
 7         s += each
 8     print("The sum of the numbers is", s)
 9 
10 main()

14.编程计算用户输入的一系列数字的平均值。与前面的问题一样,程序会首先询问用户有多少个数字。注意:平均值应该始终为 float,即使用户输入都是 int。

 1 #   A program to find the average of a series of numbers entered by the user
 2 def main():
 3     n = int(input("How many numbers are to be calculated? "))
 4     s = 0
 5     for i in range(1, n + 1):
 6         each = float(input("Please enter a number"))
 7         s += each
 8     avg = s / n
 9     print("The average is", avg)
10 
11 main()

15.编写程序,通过对这个级数的项进行求和来求近似的 π 值:4/1 – 4/3 + 4/5 – 4/7 + 4/9 − 4/11 + …… 程序应该提示用户输入 n,要求和的项数,然后输出该级数的前n 个项的和。让你的程序从math.pi 的值中减去近似值,看看它的准确性。

 1 #   A program to approximate the value of pi by summing the terms 
 2 #   of this series: 4/1 - 4/3 + 4/5 = 4/7 + 4/9 - 4/11 + ...
 3 import math
 4 def main():
 5     estimate = 0
 6     n = int(input("Please enter the number of terms to sum: "))
 7     for k in range(1, n + 1):
 8         estimate += (-1) ** (k + 1) * 4 / (2 * k - 1)
 9     error = abs(math.pi - estimate)
10     print("""The approximation of pi is {0}, which is {1} 
11     away from the value of math.pi({2})""".format(estimate, error, math.pi))
12 
13 main()
14 # Output:
15 # Please enter the number of terms to sum: 10000000
16 # The approximation of pi is 3.1415925535897915, which is 1.0000000161269895e-07
17 #     away from the value of math.pi(3.141592653589793)
莱布尼兹恒等式:

看起来很帅,但是,该级数收敛起来非常慢。


  16.斐波那契序列是数字序列,其中每个连续数字是前两个数字的和。经典的斐波那契序列开始于 1,1,2,3,5,8,13,……。编写计算第n 个斐波纳契数的程序,其中 n 是用户输入的值。例如,如果 n = 6,则结果为 8。

 

 1 #   A program to compute the nth Fibonacci number where n is a value input by the user
 2 def fibonacci(n):
 3     if n <= 0:
 4         raise ValueError("n must be positive") 
 5     elif n < 2:
 6         return n
 7     fib_n_minus_one = 1
 8     fib_n_minus_two = 0
 9     fib_n = 0
10     for _ in range(2, n + 1):
11         fib_n = fib_n_minus_one + fib_n_minus_two
12         fib_n_minus_two = fib_n_minus_one
13         fib_n_minus_one = fib_n
14     return fib_n
15 
16 def main():
17     n = int(input("n = "))
18     fib_n = fibonacci(n)
19     print("The {0}th Fibonacci number is {1}".format(n, fib_n))
20 
21 main()

17.你已经看到 math 库包含了一个计算数字平方根的函数。在本练习中,你将编写自己的算法来计算平方根。解决这个问题的一种方法是使用猜测和检查。你首先猜测平方根可能是什么,然后看看你的猜测是多么接近。你可以使用此信息进行另一个猜测,并继续猜测,直到找到平方根(或其近似)。一个特别好的猜测方法是使用牛顿法。假设 x 是我们希望的根,guess 是当前猜测的答案。猜测可以通过使用计算下一个猜测来改进:

编程实现牛顿方法。程序应提示用户找到值的平方根(x)和改进猜测的次数。从猜测值 x / 2 开始,你的程序应该循环指定的次数,应用牛顿的方法,并报告猜测的最终值。你还应该从 math.sqrt(x) 的值中减去你的估计值,以显示它的接近程度。

 1 #   A program to implement Newton's method
 2 import math
 3 def main():
 4     x = float(input("Please enter the number we want the root of: "))
 5     times = int(input("Please enter the number of times to loop: "))
 6     guess = x / 2
 7     for _ in range(times):
 8         guess = (guess + x / guess) / 2
 9     root = math.sqrt(x)
10     error = abs(root - guess)
11     print("The final value of guess is {0}, which is {1} away from {2}".format(\
12     guess, error, root))
13 
14 main()

 



 

posted @ 2018-11-23 08:41  梨花梦蝶  阅读(5467)  评论(0编辑  收藏  举报