第六章
1
line = "After fresh rain in mountains bare " print(line.title())
2
a = float(input("输入三角形第一条直角边长:")) b = float(input("输入三角形第二条直角边长:")) area = a*b*0.5 print("直角三角形的面积为:{:.1f}".format(area))
3
num = eval(input("输入数字:")) print("对应的二进制数:{0:b}\n八进制数:{0:o}\n十六进制数:{0:X}".format(num))
4
import turtle turtle.color('black','yellow') turtle.begin_fill() turtle.circle(50) turtle.end_fill()
5
def judge_year(year): if (year%4==0 and year%100!=0) or year%400==0: print(year,"年是闰年") else: print(year, "年不是闰年") year = eval(input("请输入年份:")) judge_year(year)
6
fi = open("score.csv", "r") fo = open("avg-score.txt", "w") ls = [] x = [] sum = 0 for row in fi: ls.append(row.strip("\n").split(",")) for line in ls[1:]: for i in line[1:]: sum = int(i) + sum avg = sum / 3 x.append(avg) sum = 0 fo.write("语文:{:.2f}\n数学:{:.2f}\n英语:{:.2f}\n物理:{:.2f}\n科学:{:.2f}".format(x[0], x[1], x[2], x[3], x[4])) fi.close() fo.close()
第七套
1
lis = [2,8,3,6,5,3,8] new_lis = list(set(lis)) print(new_lis)
2
fruit = input('输入水果:') lis = ['苹果','哈密瓜','橘子','猕猴桃','杨梅','西瓜'] if fruit in lis: print(fruit+"在列表lis中") else: print(fruit+"不在列表lis中")
3
def str_change(str) : return str[::-1] str = input("输入字符串:") print(str_change(str))
4
import turtle turtle.color("black","yellow") turtle.begin_fill() for i in range(5): turtle.fd(200) turtle.right(144) turtle.end_fill()
5
lower = int(input('输入区间最小值:')) upper = int(input('输入区间最大值:')) for num in range(lower+1,upper): if num>1: for i in range(2,num): if(num%i)==0: break else: print(num)
6
fo = open("PY301-1.txt","w") class Horse(): def __init__(self, category, gender, age): self.category = category self.gender = gender self.age = age def get_descriptive(self): self.info = "一匹" + self.category + str(self.age) + "岁的" + self.gender + "马" def write_speed(self, new_speed): self.speed = new_speed addr = "在草原上奔跑的速度为" fo.write(self.info + "," + addr + str(self.speed) + "km/h。") horse = Horse("阿拉伯","公",12) horse.get_descriptive() horse.write_speed(50) fo.close()
fo = open("PY301-2.txt","w") class Horse(): def __init__(self, category, gender, age): self.category = category self.gender = gender self.age = age def get_descriptive(self): self.info = "一匹" + self.category + str(self.age) + "岁的" + self.gender + "马" def write_speed(self, new_speed): self.speed = new_speed addr = "在草原上奔跑的速度为" fo.write(self.info + "," + addr + str(self.speed) + "km/h。") class Camel(Horse): def __init__(self, category, gender, age): super().__init__(category, gender, age) def write_speed(self,new_speed): self.speed = new_speed addr = "在沙漠上奔跑的速度为" fo.write(self.info.replace("马","骆驼") + "," + addr + str(self.speed) + "km/h。") camel = Camel("双峰驼","母",20) camel.get_descriptive() camel.write_speed(40) fo.close()
第八套
1
animals = ['cow', 'duck', 'cat', 'dog'] animals.reverse() # animals = animals[::-1] print(animals)
2
word = " 窗前明月光,疑是地上霜。 " print(word.strip())
3
count = 0 while count < 50: count+=1 if count % 2 == 0: continue print(count,end=",")
4
import turtle for i in range(4): turtle.seth(90*(i+1)) turtle.circle(50,90) turtle.seth(90*(i-1)) turtle.circle(50,90) turtle.hideturtle()
5
import math try: a = eval(input('请输入底数:')) b = eval(input('请输入真数:')) c = math.log(b, a) except ValueError: if a<=0 and b>0: print("底数不能小于等于0") elif b<=0 and a>0: print("真数不能小于等于0") elif a<=0 and b<=0: print('真数和低数都不能小于等于0') except ZeroDivisionError: print('底数不能为1') except NameError: print('输入必须为实数') else: print(c)
6
intxt = input("请输入明文:") for p in intxt: if "a" <= p <= "z": print(chr(ord("a") + (ord(p) - ord("a") + 3)%26), end="") elif "A" <= p <= "Z": print(chr(ord("A") + (ord(p) - ord("A") + 3)%26), end="") else: print(p,end="")
第九套
1
while True: s = input("请输入信息:") if s=="Y" or s=="y": break
2
import calendar year = int(input("请输入年份:")) table = calendar.calendar(year) print(table)
3
s = input("请输入绕口令:") print(s.replace("兵","将"))
4
5
fo = open("PY202.txt","w") for i in range(1,10): for j in range(1,i+1): fo.write("{}*{}={}\t".format(j,i,i*j)) fo.write("\n") fo.close()
6
fi = open("关山月.txt","r") fo = open("关山月-诗歌.txt","w") for i in fi.read(): if i == "。": fo.write("。\n") else: fo.write(i) fi.close() fo.close()
fi = open("关山月-诗歌.txt","r") fo = open("关山月-反转.txt","w") txt = fi.readlines() txt.reverse() for line in txt: fo.write(line) fi.close() fo.close()
第十套
1
data = eval(input("请输入一组数据,以逗号分隔:")) print(max(data))
2
import jieba s = "一件事情没有做过,就没有资格对此事发表看法" ls = jieba.lcut(s) print(ls)
3
这题不会
import time t = time.localtime() print(time.strftime("%Y年%m月%d日%H时%M分%S秒",t))
4
for i in range(0, 4): for y in range(0, 4 - i): print(" ", end="") print("* " * i) for i in range(0, 4): for x in range(0, i): print(" ", end="") print("* " * (4 - i))
5
from turtle import * pensize(5) for i in range(6): fd(100) right(60) color("red") circle(60,steps=6)
6
import random letter_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] letter = letter_list[random.randint(0, 25)] count = 0 while True: a = input("请输入猜测的字母:") count += 1 if a not in letter_list: print("请重新输入字母:") else: if count >= 5: print("你答错了5次,结束游戏!") break elif a > letter: print("输入的字母在答案之后") continue elif a < letter: print("输入的字母在答案之前") continue elif a == letter: print("恭喜你答对了!共回答了{}次".format(count)) break
第十一套
1
f = open("poem.txt","r") result = [] for line in f.readlines(): line = line.strip("\n") if len(line) != 0 and line[0] != "#": result.append(line) result.sort() for line in result: print(line) f.close()
2
a = [] for i in range(8): a.append([]) for j in range(8): a[i].append(0) for i in range(8): a[i][0] = 1 a[i][i] = 1 for i in range(2,8): for j in range(1,i): a[i][j] = a[i-1][j-1]+a[i-1][j] for i in range(8): for j in range(i+1): print("{:3d}".format(a[i][j]),end=" ") print()
3
def proc(strings): m = 0 lst = [] for i in range(len(strings)): if len(strings[i]) > m: m = len(strings[i]) for i in range(len(strings)): if len(strings[i]) == m: lst.append(strings[i]) return lst strings = ['cad' ,'VB', 'Python', 'MATLAB', 'hello', 'world'] result = proc(strings) print("the longest words are:") for item in result: print("{: >25}".format(item))
4
strings = {'cad', 'PE ', 'Window', 'FM', 'hello', 'world','flowers'} n=0 for word in strings: if word.islower(): n += 1 print(n)
5
def proc(stu_list): d = {} for item in stu_list: r = item.split("_") a,b = r[0],r[1].strip() if a in d: d[a] += [b] else: d[a] = [b] lst = sorted(d.items(), key = lambda d:len(d[1]), reverse = True) return lst f = open("signup.txt","r") stu_list = f.readlines() result = proc(stu_list) for item in result: print(item[0], '->', item[1]) f.close()
6
d = {"lili": 80, "xiaoqiang": 75, "yunyun": 89, "yuanyuan": 90, "wanghao": 85} d_sort = sorted(d.items(), key=lambda x: x[1], reverse=True) for i in range(3): print(d_sort[i][0] + " " + str(d_sort[i][1]))
第十二套
1
num = input().split(",") for i in num: print("{:>10}".format(i),end='')
2
scale = 0.0001 # 成就值增量 def calv(base, day): val = base * pow(1+scale,day*11) return val print('5年后的成就值是{}'.format(int(calv(1, 5*365)))) year = 1 while calv(1, year*365) < 100: year += 1 print('{}年后成就值是100'.format(year))
3
while True: try: a = eval(input('请输入一个正整数: ')) if a > 0 and type(a)==int: print(a) break else: print("请输入正整数") except: print("请输入正整数")
4
import turtle as t ls = [69, 292, 33, 131, 61, 254] X_len = 400 Y_len = 300 x0 = -200 y0 = -100 t.penup() t.goto(x0, y0) t.pendown() t.fd(X_len) t.fd(-X_len) t.seth(90) t.fd(Y_len) t.pencolor('red') t.pensize(5) for i in range(len(ls)): t.penup() t.goto(x0 + (i+1)*50, -100) t.seth(90) t.pendown() t.fd(ls[i]) t.done()
5
import random random.seed(2) pdict = {'Alice': ['123456789'], 'Bob': ['234567891'], 'Lily': ['345678912'], 'Jane': ['456789123']} name = input('请输入一个人名:') plist = list(pdict) if name in plist: print(name, pdict.get(name)[0], random.randint(1000,9999)) else: print("对不起,您输入的用户信息不存在。")
6
import jieba def fenci(txt): f = open(txt, "r") datas = f.read() f.close() data = jieba.lcut(datas) d = {} for i in data: if len(i) >= 2: d[i] = d.get(i, 0) + 1 lt = list(d.items()) lt.sort(key=lambda x: x[1], reverse=True) return lt def show(lt): for i in lt[:9]: print(i[0], ":", i[1], end=',',sep="") print(lt[9][0], ":", lt[9][1],sep="") l1 = fenci("data2018.txt") l2 = fenci("data2019.txt") print(2019, end=':') show(l2) print(2018, end=':') show(l1)
import jieba def fenci(txt): f = open(txt, "r") datas = f.read() f.close() data = jieba.lcut(datas) d = {} for i in data: if len(i) >= 2: d[i] = d.get(i, 0) + 1 lt = list(d.items()) lt.sort(key=lambda x: x[1], reverse=True) ls = [x[0] for x in lt[:10]] return ls def show(lt): print(','.join(lt)) l1 = fenci("data2018.txt") l2 = fenci("data2019.txt") l3 = [] for i in l1: if i in l2: l3.append(i) for i in l3: l1.remove(i) l2.remove(i) print("共有词语:", end='') show(l3) print('2019特有:', end='') show(l2) print('2018特有:', end='') show(l1)