《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()

 



 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM