python嵩天课后思考题_Python语言程序设计基础(第二版)嵩天等课后习题答案

第一次博文 Time:2018年04月28日 星期六 11:37

二次补充 2018年05月02日

第一章 程序设计基本方法 P29

# 1.1字符串的拼接

str1 = input("请输入一个人的名字:")

str2 = input("请输入一个地点:")

print("世界这么大,{}想去{}看看。".format(str1,str2))1234

# 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)1234567

# 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('')1234567891011121314151617

# ---------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)123456

# ---------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)123456

# --------1.6 健康食谱输出 ------------------------#

diet = ['西红柿','土豆','鸡蛋','黄瓜','青菜']

for i in range(5):

for j in range(5):

if (i != j):

print(diet[i],diet[j],sep = '炒')123456

# --------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()1234567891011

# ------1.8 太阳花的绘制 --------------------------#

from turtle import *

color('red','yellow')

begin_fill()

while True:

forward(200)

left(170)

if abs(pos()) <1:

break

end_fill()

done()1234567891011

第二章 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("输入格式错误")12345678910

# -----------------循环输入----------------------------------#

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("请输入带有符号的温度值:")123456789101112

# --------------------------正方形的绘制---------------------------------#im

import turtle as t

t.pensize(3)

for i in range(1,5):

t.fd(100)

t.setheading(90*i)

t.done()1234567

# --------------------------六边形的绘制---------------------------------#im

import turtle as  t

t.pensize(3)

for i  in range(6):

t.fd(100)

t.seth(60+60*i)

t.done()1234567

# --------------------------叠边形的绘制---------------------------------#im

import turtle as  t

t.pensize(3)

for i  in range(9):

t.fd(150)

t.seth(80+80*i)

t.done()1234567

# --------------------------同切圆的绘制---------------------------------#im

import turtle as  t

t.pensize(3)

for i in range(4):

t.circle(50+i*10)

t.done()123456

# ----------------------------长度转换------------------#

# 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("输入格式错误")1234567891011

# ------------------------多彩蟒蛇的绘制---------------------------------#

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

第三章 基本数据类型

天天向上的力量

在一年中,如果每天进步》》,那么一年下来会进步到多少呢?

在一年中,如果每天退步》》,那么一年下来会倒退到多少呢?

一年中每天提升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))

123456

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))1234

#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))123456

#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))123456789

#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))12345678910111213

第四章 程序的控制结构 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))123456789101112

# 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))12345678910111213

# 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))123456789

# 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))12345678910111213

# 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))

break1234567891011121314151617181920

# 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))1234567891011121314

第六章 组合数据类型 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()12345678910111213141516171819

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

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("请输入要分析的字符串,回车表示结束:")1234567891011121314151617

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

---------------------

作者:GTFQAQ

  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值