1. 程式人生 > >Python語言程式設計基礎(第二版)嵩天等課後習題答案

Python語言程式設計基礎(第二版)嵩天等課後習題答案

第一次博文 Time:2018年04月28日 星期六 11:37
二次補充 2018年05月02日
第一章 程式設計基本方法 P29

# 1.1字串的拼接
str1 = input("請輸入一個人的名字:")
str2 = input("請輸入一個地點:")
print("世界這麼大,{}想去{}看看。".format(str1,str2))
# 1.2整數序列求和
n = input("請輸入一個整數N:")
sum = 0
for i in range(int(n)):#或者調和函式eval(n)
   print(i,end = ' ')
   sum = sum + i+1
print("1到N求和結果為:"
,sum)
# 1.3 9*9乘法表
# 版本一
for i in range(1,10):
   for m in range(1,i+1):
       sum = i*m
       if m < i:
           if sum < 10:
               print(m,'*',i,"= {}".format(sum),end = '  ')
           else:
               print(m,'*',i,'=',sum,end = ' ')
       else:
           print(m,'*',i,'='
,sum) # 版本二 for i in range(1,10): for j in range(1,i+1): print("{} * {} = {:2}".format(j,i,i*j),end = ' ') print('')
# ---------1.4 計算1+2!+3!+4!+...+10!------------#
sum,tmp = 0,1
for i in range(1,11):
   tmp *= i
   sum += tmp
print("1+2!+3!+4!+...+10!=",sum)
# ---------1.5 猴子吃桃問題 ----------------------#
# list(range(5,0,-1)) ----- [5, 4, 3, 2, 1] n = 1 for i in range(5,0,-1): n = (n+1)*2 #n = (n+1)<<1 左移一位乘以2 print(n)
# --------1.6 健康食譜輸出 ------------------------#
diet = ['西紅柿','土豆','雞蛋','黃瓜','青菜']
for i in range(5):
   for j in range(5):
       if (i != j):
           print(diet[i],diet[j],sep = '炒')
# --------1.7 繪製五角星 --------------------------#
from turtle import *
##fillcolor("red")
color('red','yellow') #color('線條顏色','填充顏色')
begin_fill()
while True:
   forward(200)
   right(144)
   if abs(pos()) < 1:
       break
end_fill()
# ------1.8 太陽花的繪製 --------------------------#
from turtle import *
color('red','yellow')
begin_fill()
while True:
   forward(200)
   left(170)
   if abs(pos()) <1:
       break
end_fill()
done()

第二章 Python程式例項解析

# ---------------溫度轉換程式1.1 P35-------------------------#
TempStr = input("請輸入帶有符號的溫度值:")
if TempStr[-1] in ['F','f']:
   C = (eval(TempStr[0:-1]) - 32) / 1.8
   print("華氏溫度{}轉換為攝氏度溫度是:{:.2f}C".format(TempStr,C))
elif TempStr[-1] in ['C','c']:
   F = eval(TempStr[0:-1])*1.8 + 32
   print("攝氏溫度{}轉換為華氏溫度是:{:.2f}F".format(TempStr,F))
else:
   print("輸入格式錯誤")
# -----------------迴圈輸入----------------------------------#
TempStr = input("請輸入帶有符號的溫度值:")
while TempStr[-1] not in ['N','n']:
   if TempStr[-1] in ['F','f']:
       C = (eval(TempStr[0:-1]) - 32) / 1.8
       print("華氏溫度{}轉換為攝氏度溫度是:{:.2f}C".format(TempStr,C))
   elif TempStr[-1] in ['C','c']:
       F = eval(TempStr[0:-1])*1.8 + 32
       print("攝氏溫度{}轉換為華氏溫度是:{:.2f}F".format(TempStr,F))
   else:
       print("輸入格式錯誤")
   TempStr = input("請輸入帶有符號的溫度值:")
# --------------------------正方形的繪製---------------------------------#im
import turtle as t
t.pensize(3)
for i in range(1,5):
   t.fd(100)
   t.setheading(90*i)
t.done()
# --------------------------六邊形的繪製---------------------------------#im
import turtle as  t
t.pensize(3)
for i  in range(6):
   t.fd(100)
   t.seth(60+60*i)
t.done()
# --------------------------疊邊形的繪製---------------------------------#im
import turtle as  t
t.pensize(3)
for i  in range(9):
   t.fd(150)
   t.seth(80+80*i)
t.done()
# --------------------------同切圓的繪製---------------------------------#im
import turtle as  t
t.pensize(3)
for i in range(4):
   t.circle(50+i*10)
t.done()
# ----------------------------長度轉換------------------#
# 1米 = 39.37英寸
le = input()
if le[-1] in ['M','m']:
   temp = eval(le[0:-1]) * 39.37
   print("{:.3f}in".format(temp))
elif le[-2:] in ['in','IN']:
   temp = eval(le[0:-2]) / 39.37
   print("{:.3f}m".format(temp))
else:
   print("輸入格式錯誤")
# ------------------------多彩蟒蛇的繪製---------------------------------#
import turtle as t
week = ['black','grey','darkgreen','gold','violet','purple','green','red']
def drawSnake(r,angle,length):
   t.seth(-40)
   for i in range(length):
       t.pencolor(week[i%8])
       t.circle(r,angle)
       t.pencolor(week[(i+1)%8])
       t.circle(-r,angle)
   t.circle(r,angle/2)
   t.fd(40)
   t.circle(16,180)
   t.fd(40*2/3)
t.setup(650,350)
t.penup()
t.fd(-250)
t.pendown()
t.pensize(25)
drawSnake(40,80,9)
t.done()

第三章 基本資料型別
天天向上的力量
在一年中,如果每天進步》》,那麼一年下來會進步到多少呢?
在一年中,如果每天退步》》,那麼一年下來會倒退到多少呢?

  • 一年中每天提升0.001:1.44,一年中每天能力下降0.001:0.69
  • 一年中每天提升0.005:6.17,一年中每天能力下降0.005:0.16
  • 一年中每天提升0.01:37.78,一年中每天能力下降0.01:0.03
  • 向上5天向下2天的力量:4.63。
  • 工作日多努力每天的努力應達到:0.019
# 1.1 每天的改變在千分之一 P74
import math
dayup = math.pow((1+0.001),365)
daydown = math.pow((1-0.001),365)
print("一年中每天提升0.001:{:.2f},一年中每天能力下降0.001:{:.2f}".format(dayup,daydown))
import math
dayup = math.pow((1+0.005),365)
daydown = math.pow((1-0.005),365)
print("一年中每天提升0.005:{:.2f},一年中每天能力下降0.005:{:.2f}".format(dayup,daydown))
#1.3 每天的改變在百分之一
import math
dayfactor = 0.01
dayup = math.pow((1+dayfactor),365)
daydown = math.pow((1-dayfactor),365)
print("一年中每天提升0.01:{:.2f},一年中每天能力下降0.01:{:.2f}".format(dayup,daydown))
#1.4 在每年的365天中,每週工作5個工作日,工作日每天提升0.01,
#休息兩天,休息時每天下降0.01
dayup,dayfactor = 1.0,0.01
for i in range(365):
   if i%7 in [6,0]:
       dayup *= (1 - dayfactor)
   else:
       dayup *= (1 + dayfactor)
print("向上5天向下2天的力量:{:.2f}。".format(dayup))
#1.5 問工作日多努力才能達到365天每天都工作的成績
def daydayUp(df):
   dayup = 1.0
   for i in range(365):
       if i%7 in [6,0]:
           dayup *= (1 - 0.01)
       else:
           dayup *= (1 + df)
   return dayup
dayfactor = 0.01
while(daydayUp(dayfactor) < 37.78):
   dayfactor += 0.001
print("每天的努力應達到:{:.3f}".format(dayfactor))

第四章 程式的控制結構 P121

# 4.1 猜數字遊戲
k = 5
x = eval(input("請輸入0~9之間的整數"))
tem = 0
while x != k:
    tem += 1
    if(x > k):
        print("遺憾,太大了")
    else:
        print("遺憾,太小了")
    x = eval(input("請輸入0~9之間的整數"))
print("預測{}次,你猜中了".format(tem))
# 4.2 統計不同字元個數
c,n,b,o = 0,0,0,0 # c代表字元個數 n代表數字個數 b代表空格個數 o代表其他字元個數
strs = input("請隨意輸入一行字元,包含字母,數字,空格或其他字元:")
for s in strs:
    if ord('a') <= ord(s) <= ord('z') or ord('A') <= ord(s) <= ord('Z'):
        c += 1
    elif ord('0') <= ord(s) <= ord('9'):
        n += 1
    elif ord(' ') == ord(s):
        b += 1
    else:
        o += 1
print("包含字母{0}個,數字{1}個,空格{2}個,其他字元{3}個".format(c,n,b,o))
# 4.3 最大公約數的計算
m,n = eval(input("請輸入連個整數,中間以逗號隔開"))
x,y = m,n
r = m % n
while r != 0:
    m,n = n,r
    r = m % n

print("{}和{}的最大公約數:{};最小公倍數:{:.0f}".format(x,y,n,x*y/n))
# 4.4 猜數遊戲續
import random
k = random.randint(0,100)
x = eval(input("請輸入0~100之間的整數"))
tem = 0
while x != k:
    tem += 1
    if(x > k):
        print("遺憾,太大了")
    else:
        print("遺憾,太小了")
    x = eval(input("請輸入0~100之間的整數"))
print("預測{}次,你猜中了".format(tem))
# 4.5 猜數字續
import random
while True:
    try:
        k = random.randint(0, 100)
        x = int(input("請輸入0~100之間的整數"))
        tem = 0
        while x != k:
            tem += 1
            if (x > k):
                print("遺憾,太大了")
            else:
                print("遺憾,太小了")
            x = eval(input("請輸入0~100之間的整數"))

    except:
        print("輸入內容必須為整數!")
    else:
        print("預測{}次,你猜中了".format(tem))
        break
# 4.5 羊車門問題 思想:大量樣本以頻率代替概率
import random
a = ['羊1', '羊2', '汽車']
times = 1000*1000  # 嘗試次數
first, change = 0, 0
for i in range(times):
    x = random.choice(a)  # 正確答案
    y = random.choice(a)  # 參賽者選擇答案
    if x == y:   # 堅持最初的選擇
        first += 1
    else:         # 改變選擇
        change += 1
print("堅持初心獲得勝利的概率:{:.2f}%".format(first/times*100))
print("改變初心獲得勝利的概率:{:.2f}%".format(change/times*100))

第六章 組合資料型別 P180
6.1要求
編寫程式,在16個字元大小寫和9個數字組成的列表中隨機生成10個8為密碼。

#first 1 隨機密碼生成

# 匯入random庫,後續生成0~61之間的隨機整數
import random
# 新建列表型別儲存字串和數字
strs = []
# 新增字元
for i in (65,97):
    for j in range(26):
        strs += chr(i+j)
# 新增數字
for i in range(10):
    strs += str(i)
# 輸出10個8位的密碼
for i in range(10):
    print("密碼", i+1, ":",end= '')
    for j in range(8):
        print(strs[random.randint(0,61)], end= '')
    print()

6.2重複元素判定
編寫一個函式,接受列表作為引數,如果一個元素在列表中出現了不知一次,則返回True,但不要改變原來列表的值。同時編寫呼叫這個函式和測試結果的程式。

思路:利用集合的無重複性實現

#second 2 重複元素判定
def testReEle(lis):
    tem = set(lis)
    if len(tem) == len(lis):
        print('True')
    else:
        print('False')
def getList():
    lis = []
    ch = input("請輸入判定元素,回車表示結束:")
    while ch != '':
        lis.append(ch)
        ch = input("請輸入判定元素,回車表示結束:")
    testReEle(lis)
getList()

6.3文字字元分析
編寫程式接收字串,按照字元出現頻率的降序列印字母。

# 文字字元分析
str = input("請輸入要分析的字串,回車表示結束:")
while str != '':
    # 建立字典型別儲存結果
    counts = {}
    # 掃描字串,統計出現頻率
    for ch in str:
        counts[ch] = counts.get(ch,0) + 1
    # 改變型別為列表型別,按照出現頻率降序排列
    items = list(counts.items())
    # 利用sort函式排序
    items.sort(key= lambda x : x[1],reverse= True)
    # 列印輸出
    for i in range(len(items)):
        word, count = items[i]
        print("{0:<10}{1:>5}".format(word, count))
    str = input("請輸入要分析的字串,回車表示結束:")

6.5 生日悖論分析

# 生日駁論分析 樣本太大時,執行時間會相應延長
# 思路:利用隨機函式隨機生成1~365中隨機數字,以列表儲存生成的23個數字,利用集合判斷是否重複
#       大樣本分析中,出現重複count+1,最後統計出現重複的資料所佔的比例
import random
# 大樣本次數
times = 1000*1000
# 統計生日相同的次數
count = 0
for i in range(times):
    # 建立列表型別,儲存23個人的生日在當年的某一天
    lis = []
    for j in range(23):
        lis.append(random.randint(1,365))
    # 利用集合的無重複性,轉換為集合型別儲存
    items = set(lis)
    if len(items) != len(lis):
        count += 1
print("至少兩人生日相同的概率:{:.2f}%".format(count/times*100))