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

《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.在现代 Python 中,int 值大于底层硬件 int 时,会________________。
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)。如果表达式是非法的,请解释为什么。
第 3 章 讨论 1

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 在这种情况下实际上做了什么。

Python 环境:Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32

310.0(参阅 round() 函数)

n = 314.159265
s = str(n)
l = s.split('.')
for i in range(-len(l[0]), len(l[1]) + 1):
    print('round({0}, {1}) = {2}'.format(n, i, round(n, i)))
# Output:
# round(314.159265, -3) = 0.0
# round(314.159265, -2) = 300.0
# round(314.159265, -1) = 310.0
# round(314.159265, 0) = 314.0
# round(314.159265, 1) = 314.2	①
# round(314.159265, 2) = 314.16
# round(314.159265, 3) = 314.159
# round(314.159265, 4) = 314.1593
# round(314.159265, 5) = 314.15927	③
# round(314.159265, 6) = 314.159265

for i in range(-2, 3):
    print('round(0.5, {0}) = {1}'.format(i, round(0.5, i)))
# Output:
# round(0.5, -2) = 0.0
# round(0.5, -1) = 0.0
# round(0.5, 0) = 0.0	②
# round(0.5, 1) = 0.5
# 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)。.

结论:

  1. round 函数用于对浮点数进行四舍五入求值,具体保留几位小数,由传入的 ndigits 参数来控制
  2. ndigits 是可选参数,当不传入时,即以默认保留 0 位小数进行取整,返回的是整数
  3. ndigits 传入 0 时,与不传入时一样以保留 0 位小数进行取整,但返回的是浮点数
  4. ndigits 传入正数时,取整到 ndigits 位小数,整数部分不变,返回的是浮点数。如果传入的浮点数的小数部分的位数小于 ndigits 位,则返回原来的数
  5. ndigits 传入负数时,对整数部分的后 abs(ndigits) 位进行取整( 例如:ndigits 为 -3,则对整数部分的后 3 位进行取整),小数部分清 0,返回的是浮点数。如果 ndigits 的绝对值大于传入的浮点数的整数部分的位数,则返回 0.0
  6. 当值距离两边的整数的距离相等时的取整方法,根据官方文档,Python 2.x 与 Python 3.x 的具体实现是不同的,这里只讨论 Python 3.x 的情况。这里需要提到一种取整方法,Banker’s rounding 算法(银行家舍入法)。简单地说就是,如果舍弃部分左边的数字为奇数,则向上取整(如 ①);如果舍弃部分左边的数字为偶数,则向下取整(如 ②)(参考链接
  7. (浮点运算的一个问题)查看 ③ 的结果,按照上面的规则,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

Python 环境:Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32

>>> -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.编写一个程序,利用球体的半径作为输入,计算体积和表面积。以下是一些可能有用的公式:
V = 4 / 3 π r 3 V = 4/3πr^3 V=4/3πr3
A = 4 π r 2 A = 4πr^2 A=4πr2

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

main()

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

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

main()

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

原子摩尔质量(克/摩尔)
H1.00794
C12.0107
O15.9994
例如,水(H2O)的分子量为2(1.00794)+ 15.9994 = 18.01528。
#   A program to compute the molecular weight of a hydrocarbon
import math
def main():
    hydrogen_atoms = float(input("Please enter the number of hydrogen atomes: "))
    carbon_atoms = float(input("Please enter the number of carbon atomes: "))
    oxygen_atoms = float(input("Please enter the number of oxygen atomes: "))
    
    molar_mass = dict({"H": 1.00794, "C": 12.0107, "O": 15.9994})
    molecular_weight = hydrogen_atoms * molar_mass["H"] + carbon_atoms * molar_mass["C"] \
    + oxygen_atoms * molar_mass["O"]
    print("The molecular weight of all the atoms is",   molecular_weight)

main()

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

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

main()

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

#   A program that calculates the cost of an order
def main():
    account = float(input("How many pounds of coffee do you want? "))
    coffee_cost = pounds * 10.5
    shipping = pounds * 0.86 + 1.50
    print("Cost of coffee:", coffee_cost)
    print("Shipping:      ", shipping)
    print("-------------------------------")
    print("Total due:     ", coffee_cost + shipping)

main()

6.使用坐标(x1,y1)和(x2,y2)指定平面中的两个点。编写一个程序,计算通过用户输入的两个(非垂直)点的直线的斜率。
斜率 = y 2 − y 1 x 2 − x 1 斜率 = \frac{y2-y1}{x2-x1} 斜率=x2x1y2y1

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

7.编写一个程序,接受两点(见上一个问题),并确定它们之间的距离。
距离 = ( x 2 − x 1 ) 2 + ( y 2 − y 1 ) 2 距离=\sqrt{(x2-x1)^2+(y2-y1)^2} 距离=(x2x1)2+(y2y1)2

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

main()

8.格里高利闰余是从 1 月1 日到前一个新月的天数。此值用于确定复活节的日期。它由下列公式计算(使用整型算术):
C = y e a r / / 100 C = year//100 C=year//100
e p a c t = ( 8 + ( C / / 4 ) − C + ( ( 8 C + 13 ) / / 25 ) + 11 ( y e a r % 19 ) ) % 30 epact = (8 + (C//4) - C + ((8C + 13)//25) + 11(year\%19))\%30 epact=(8+(C//4)C+((8C+13)//25)+11(year%19))%30
编写程序,提示用户输入4 位数年份,然后输出闰余的值。

#   A program to figure out the Gregorian epact value of year
import math
def main():
    year = int(input("Enter the year (e.g. 2020): "))
    C = year // 100
    epact = (8 + (C//4) - C + ((8 * C + 13) // 25) + 11 * (year % 19)) % 30
    print("The epact value is", epact, "days.")

main()

关于如何确定复活节的日期的参考链接:
http://www.madore.org/~david/misc/calendar.html)
https://www.dateofeaster.com/

9.使用以下公式编写程序以计算三角形的面积,其三边的长度为 a、b 和 c:
s = a + b + c 2 s=\frac{a+b+c}{2} s=2a+b+c
A = s ( s − a ) ( s − b ) ( s − c ) A=\sqrt{s(s-a)(s-b)(s-c)} A=s(sa)(sb)(sc)

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

10.编写程序,确定梯子斜靠在房子上时,达到给定高度所需的长度。梯子的高度和角度作为输入。计算长度使用公式为:
l e n g t h = h e i g h t s i n   a n g l e length=\frac{height}{sin\ angle} length=sin angleheight
注意:角度必须以弧度表示。提示输入以度为单位的角度,并使用以下公式进行转换:
r a d i a n s = π 180 d e g r e e s radians=\frac{\pi}{180}degrees radians=180πdegrees

#   A program to determine the length of a ladder required 
#   to reach a given height when leaned against a house
import math
def main():
    height = float(input("height: "))
    degrees = float(input("angle(in degrees): "))
    radians = math.pi / 180 * angle
    length = height / math.sin(radians)
    print("length:", length)
    
main()

angle 是梯子与地面的夹角

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

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

main()

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

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

main()

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

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

main()

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

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

main()

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

#   A program to approximate the value of pi by summing the terms 
#   of this series: 4/1 - 4/3 + 4/5 = 4/7 + 4/9 - 4/11 + ...
import math
def main():
    estimate = 0
    n = int(input("Please enter the number of terms to sum: "))
    for k in range(1, n + 1):
        estimate += (-1) ** (k + 1) * 4 / (2 * k - 1)
    error = abs(math.pi - estimate)
    print("""The approximation of pi is {0}, which is {1} 
    away from the value of math.pi({2})""".format(estimate, error, math.pi))

main()
# Output:
# Please enter the number of terms to sum: 10000000
# The approximation of pi is 3.1415925535897915, which is 1.0000000161269895e-07
#     away from the value of math.pi(3.141592653589793)

莱布尼兹恒等式:
∑ k = 1 ∞ ( − 1 ) n 2 n + 1 = 4 π \sum_{k=1}^{\infty}\frac{(-1)^n}{2n+1}=4\pi k=12n+1(1)n=4π
看起来很帅,但是,该级数收敛起来非常慢?

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

#   A program to compute the nth Fibonacci number where n is a value input by the user
def fibonacci(n):
    if n <= 0:
        raise ValueError("n must be positive") 
    elif n < 2:
        return n
    fib_n_minus_one = 1
    fib_n_minus_two = 0
    fib_n = 0
    for _ in range(2, n + 1):
        fib_n = fib_n_minus_one + fib_n_minus_two
        fib_n_minus_two = fib_n_minus_one
        fib_n_minus_one = fib_n
    return fib_n

def main():
    n = int(input("n = "))
    fib_n = fibonacci(n)
    print("The {0}th Fibonacci number is {1}".format(n, fib_n))

main()

17.你已经看到 math 库包含了一个计算数字平方根的函数。在本练习中,你将编写自己的算法来计算平方根。解决这个问题的一种方法是使用猜测和检查。你首先猜测平方根可能是什么,然后看看你的猜测是多么接近。你可以使用此信息进行另一个猜测,并继续猜测,直到找到平方根(或其近似)。一个特别好的猜测方法是使用牛顿法。假设 x 是我们希望的根,guess 是当前猜测的答案。猜测可以通过使用计算下一个猜测来改进:
g u e s s + x g u e s s 2 \frac{guess+\frac{x}{guess}}{2} 2guess+guessx
编程实现牛顿方法。程序应提示用户找到值的平方根(x)和改进猜测的次数。从猜测值 x / 2 开始,你的程序应该循环指定的次数,应用牛顿的方法,并报告猜测的最终值。你还应该从 math.sqrt(x) 的值中减去你的估计值,以显示它的接近程度。

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

main()
  • 16
    点赞
  • 67
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有一只海豚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值