# python练习7——PTA

17 篇文章 34 订阅

## 7-1 jmu-python-异常-学生成绩处理专业版 (25 分)

3
1
2
3

Total: 3
OK: 3
Error: 0
avg grade = 2.00

5
1
2
a
b 5
3

line 3 error for input " a "
line 4 error for input " b 5"
Total: 5
OK: 3
Error: 2
avg grade = 2.00

5
a
2
3

line 1 error for input " a"
end of files
Total: 3
OK: 2
Error: 1
avg grade = 2.50

## 7-2 jmu-分段函数l (20 分)

1.png

-2

y=3.00

try:
x=float(input())
if x<=-2:
ans=(-2*x)-1
elif x>-2 and x<=1:
ans=3
elif x>1:
ans=2*x+1
print("y={:.2f}".format(ans))
exit(0)
except Exception as result:#这个加域不加，以及break在try里是否能用
print("Input Error!")



## 7-3 jmu-python-简单计算器 (20 分)

4
1+1
56-23
5/3
5*3.5

2.00
33.00
1.67
17.50

3
ab+23
2/0
23+36f

NameError
ZeroDivisionError
SyntaxError

times = int(input())
for _ in range(times):
exp = input()
try:
result = eval(exp)
except NameError:
print("NameError")
except ZeroDivisionError:
print("ZeroDivisionError")
except SyntaxError:
print("SyntaxError")
else:
print("%.2f"%result)


## 7-4 JMU-Python-分段函数 (20 分)

Snap5.bmp

1.5

f(1.50) = 4.55

-4

f(-4.00) = 0.00

abc

Input Error

import math as m
def demo1(x):
if x > 0:
y = m.cos(x) + m.exp(x)
elif x==0:
print("0.00")
else:
y = 0
print("f(%.2f) = %.2f" %(x,y))
try:
x = float(input())
demo1(x)
except Exception as result:
print("Input Error")#居然是这个！感叹号，我要注意细节啊！


## 7-5 JMU-Python-分段函数 (20 分)

Snap6.bmp

4

f(4.00) = 3.39

-6

f(-6.00) = 0.00

x

Input Error

import math as m
try:
x=float(input())
if x<=0:
ans=0
else:
ans=m.log(x)+m.sqrt(x)
print("f({:.2f}) = {:.2f}".format(x,ans))
except Exception as result:
print("Input Error")


## 7-6 jmu-python-查成绩 (10 分)

76

zd={}
while True:
try:
tmp=input()
if len(tmp)==1:
break
m,n=map(str,tmp.split(":"))
zd[m]=n
except:
break
if ask in zd.keys():
else:
print("没有该门课程")



## 7-7 竞赛排名 (10 分)

2
3
Jack Smith 0
Smith Bob 1
Jack Bob 1
6
a b 1
c a 0
a d 0
a e 1
f a 1
b c 1
d b 0
e b 0
f b 0
c d 1
c e 1
c f 1
d e 0
f d 0
e f 0

1 Jack Smith
3 Bob
1 c
2 a
3 b f
5 d
6 e

ZJUTOJ 1330

t=int(input())
for T in range(t):
n=int(input())
A=set()
f=[]
defen={}
num=(n*(n-1))/2
num=int(num)
for N in range(num):
s=map(str,input().split())
s=list(s)
f.append(int(s[2]))
if int(s[2])==1:
if s[0] in defen.keys():
defen[s[0]]+=3
else:
defen[s[0]]=3
elif int(s[2])==0:
if s[0] in defen.keys():
defen[s[0]]+=1
else:
defen[s[0]]=1
if s[1] in defen.keys():
defen[s[1]]+=1
else:
defen[s[1]]=1
#     print(A)
A=list(A)
A.sort()
# print("我要的")
#     print(A)
num=len(A)
ans=[]
for N in range(num):
if A[N] not in defen.keys():
defen[A[N]]=0
#     print(ans)
defent=sorted(defen.items(),key=lambda d:(-d[1],d[0]))
#     print(defent)
ans={}
dexm=0
indexn=0
for i in range(n):
indexn=i+1
tmp = defent[i][0]
#         print("tmp来了"+tmp,dexm)
if i>=1 and defent[i][1] == defent[i - 1][1] and defent[i][1]!=0:#一样的分数，要使排名相同

ans[dexm].append(tmp)
#                 print(tmp,dexm)
else:#出现不一样的分数
dexm=indexn
#                 print(str(tmp),indexn)
tmp=str(tmp)
ans[indexn]=[]
ans[indexn].append(tmp)
# 记录那个变化的排序数

#         print(ans)
for key,value in ans.items():
print("{}".format(key),end="")
for i in value:
print(" {}".format(i),end="")
print()


## 7-8 进步排行榜 (10 分)

2
6
usx15131 21 124
usx15101 27 191
usx15113 31 124
usx15136 18 199
usx15117 27 251
usx15118 21 124
10
usx15131 21 124
usx15101 27 191
usx15107 24 154
usx15113 31 124
usx15117 25 251
usx15118 21 124
usx15119 22 117
usx15121 43 214
usx15128 21 124
usx15136 28 199

1 usx15113 31 124
2 usx15117 27 251
3 usx15101 27 191
4 usx15118 21 124
4 usx15131 21 124
6 usx15136 18 199
1 usx15121 43 214
2 usx15113 31 124
3 usx15136 28 199
4 usx15101 27 191
5 usx15117 25 251
6 usx15107 24 154
7 usx15119 22 117
8 usx15118 21 124
8 usx15128 21 124
8 usx15131 21 124

#会用那个多个比较规则就好写多了
t=int(input())
for T in range(t):
n=int(input())
name=[]
d=[]
t=[]
zd={}
for N in range(n):
s=map(str,input().split())
s=list(s)
# print(s)
zd[N]=s
# print(zd)
# print(zd.values())
zdt=sorted(zd.values(),key=lambda x:(-int(x[1]),-int(x[2]),x[0]))
# print(zdt)#nice可以做到
indexn=0
indexm=0
for i in range(n):
indexn=i+1
if  i>=1 and zdt[i][1]==zdt[i-1][1] and zdt[i][2]==zdt[i-1][2]:#出现相同的
zdt[i].append(indexm)
else:
indexm=indexn
zdt[i].append(indexn)
#     print(zdt)#nice
for N in range(n):
print("{} {} {} {}".format(zdt[N][3],zdt[N][0],zdt[N][1],zdt[N][2]))



## 7-9 平均成绩 (10 分)

3
zhangsan 80 75 65
lisi 65 52 56
wangwu 87 86 95

wangwu 87 86 95 89.33
zhangsan 80 75 65 73.33

import collections
while True:#啊这，居然不要排序，而是只要逆序输出，用书上那个有顺序的字典
try:
n = int(input())
# zd = collections.OrderedDict()
zd = {}
for N in range(n):
s = map(str, input().split())
s = list(s)
# print(s)
zd[N] = s
zd[N].append((int(s[1]) + int(s[2]) + int(s[3])) / 3)
# print(zd)
#        """zdt = sorted(zd.values(), key=lambda x: (-int(x[1]), -int(x[2]), -int(x[3]), -x[4]))
for i in range(n):
ii=n-i-1
# print(ii)
# print(zd[ii][1][1])
# print(zd[ii][1])
# print(int(zd[ii][1]))
# print(zd[ii][0])
if (int(zd[ii][1])+int(zd[ii][2])+int(zd[ii][3]))<180:
continue
else:
print("{} {} {} {} {:.2f}".format(zd[ii][0],zd[ii][1], zd[ii][2], zd[ii][3], zd[ii][4]))
except:
break


## 7-10 成绩排序 (10 分)

3
zhangsan 80 75 65
lisi 65 52 56
wangwu 87 86 95

wangwu 87 86 95 89.33
zhangsan 80 75 65 73.33
lisi 65 52 56 57.67

while True:
try:
n = int(input())
zd = {}
for N in range(n):
s = map(str, input().split())
s = list(s)
# print(s)
zd[N] = s
zd[N].append((int(s[1]) + int(s[2]) + int(s[3])) / 3)
# print(zd)
zdt = sorted(zd.values(), key=lambda x: (-int(x[1]), -int(x[2]), -int(x[3]), -x[4]))
for i in range(n):
print("{} {} {} {} {:.2f}".format(zdt[i][0], zdt[i][1], zdt[i][2], zdt[i][3], zdt[i][4]))
except:
break


## 7-13 优异生查询(类和对象) (20 分)

1）属性：姓名(name)，数学成绩(mscore)，语文成绩(cscore)，英语成绩(escore)；

2）方法：

Jack Tom Jim
95 84 32
90 75 45
85 90 67

Jack 95 90 85

class Student:
def __init__(self,name,mscore,cscore,escore):
self.name=name
self.mscore=mscore
self.cscore=cscore
self.escore=escore
def getSum(self):
return self.mscore+self.cscore+self.escore
def getBest(self):#怎么把对象用进去，直接在对象间操作
return self.name,self.mscore,self.cscore,self.escore
name1=[]
name1=map(str,input().split())
name1=list(name1)
num=len(name1)
m1=[]
c1=[]
e1=[]
for i in range(3):
tmp=map(int,input().split())
if i==0:
m1=list(tmp)
elif i==1:
c1=list(tmp)
else:
e1=list(tmp)
maxn=0
maxnname=-1
for i in range(num):
tmp=Student(name1[i],m1[i],c1[i],e1[i])
if tmp.getSum()>maxn:
maxn=tmp.getSum()
maxnname=i
print("{} {} {} {}".format(name1[maxnname],m1[maxnname],c1[maxnname],e1[maxnname]))


## 7-14 解题排行 (10 分)

1
4
0010 200
1000 110
0001 200
0100 225

1 0100 225
2 0001 200
2 0010 200
4 1000 110

t=int(input())
for T in range(t):
zd={}
n=int(input())
for N in range(n):
s=map(str,input().split())
s=list(s)
zd[N]=s
zdt=sorted(zd.values(),key=lambda x:(-int(x[1]),x[0]))
# print(zdt)
indexn=0
indexm=0
for i in range(n):
indexn=i+1
if i>=1 and int(zdt[i][1])==int(zdt[i-1][1]):
zdt[i].append(indexm)
else:
indexm=indexn
zdt[i].append(indexn)
for i in range(n):
print("{} {} {}".format(zdt[i][2],zdt[i][0],zdt[i][1]))
"""1 0100 225
2 0001 200
2 0010 200
4 1000 110
"""


## 7-15 确定最终排名 (10 分)

1
8
Team22 2
Team16 3
Team11 2
Team20 3
Team3 5
Team26 4
Team7 1
Team2 4

1 Team3 5
2 Team26 4
3 Team2 4
4 Team16 3
5 Team20 3
6 Team22 2
7 Team11 2
8 Team7 1

t=int(input())
for T in range(t):
zd={}
n=int(input())
for N in range(n):
s=map(str,input().split())
s=list(s)
zd[N]=s
zdt=sorted(zd.values(),key=lambda x:(-int(x[1])))
# print(zdt)
indexn=0
indexm=0
for i in range(n):
indexn=i+1
zdt[i].append(indexn)
for i in range(n):
print("{} {} {}".format(zdt[i][2],zdt[i][0],zdt[i][1]))
"""1 0100 225
2 0001 200
2 0010 200
4 1000 110
"""


## 7-16 获奖 (10 分)

1
3 team001
team001 2 27
team002 2 28
team003 0 7

YES

T=int(input())
for z in range(T):
n,ms=input().split()
n=eval(n)
canAward=int(n*0.6+0.5)
lstS=[]
lstM=[]
lstG=[]
lst=[]
for i in range(n):
s,m,g=input().split()
m,g=int(m),int(g)
lstS.append(s)
lstM.append(m)
lstG.append(g)
nameIndex=lstS.index(ms)
lstG.sort(reverse=True)
if sortedIndex<= canAward-1:
print("YES")
else:
print("NO")


## 7-17 足球联赛排名 (10 分)

2
4
1 2 0 2
1 3 1 1
1 4 0 0
2 3 2 0
2 4 4 0
3 4 2 2
3
1 2 3 0
1 3 1 1
2 3 0 0

2 3 1 4
1 3 2

t=int(input())
for T in range(t):
n=int(input())
zd={}
dd=[]
nt=n*(n-1)
nt=int(nt/2)
for N in range(nt):#第一个名字，第1个得分，第2个胜球,第3个总进球数
s=map(int,input().split())
s=list(s)
# print(s)
tmp1=s[0]
tmp2=s[1]
if tmp1 not in zd.keys():
zd[tmp1]=[0]
zd[tmp1].append(0)
zd[tmp1].append(0)
if tmp2 not in zd.keys():
zd[tmp2]=[0]
zd[tmp2].append(0)
zd[tmp2].append(0)
# print(zd)
if s[2]==s[3]:
zd[s[0]][0]+=1
zd[s[1]][0]+=1
# print("得分")
# print(zd[s[0]][0],zd[s[1]][0])

# print("净胜球")
# print(zd[s[0]][1], zd[s[1]][1])
elif s[2]>s[3]:
# print("原来得分")
# print(zd[s[0]][0],zd[s[1]][0])
zd[s[0]][0]+=3
zd[s[1]][0]+=0
# print("得分")
# print(zd[s[0]][0])
# print(zd[s[1]][0])
# print(zd)

# print(s[2]-s[3])
zd[s[0]][1]+=int(s[2]-s[3])
zd[s[1]][1]+=int(s[3]-s[2])
# print("净胜球")
# print(zd[s[0]][1], zd[s[1]][1])
elif s[2]<s[3]:
zd[s[1]][0]+=3
# print("得分")
# print(zd[s[0]][0], zd[s[1]][0])

zd[s[0]][1]+=(s[2] - s[3])
zd[s[1]][1]+=(s[3] - s[2])
# print("净胜球")
# print(zd[s[0]][1], zd[s[1]][1])
zd[s[0]][2]+=s[2]
zd[s[1]][2]+=s[3]
zdt=sorted(zd.items(),key=lambda x:(-x[1][0],-x[1][1],-x[1][2],x[0]))
# print(zdt)
for i in range(n):
if i>=1:
print(" {}".format(zdt[i][0]),end="")
else:
print("{}".format(zdt[i][0]),end="")
print()



## 7-19 节约有理 (10 分)

1
3 3
xiwangshop kehaishop xinhuashop
11.1 22.2 33.3
11.2 22.2 33.2
10.9 22.3 33.1

xinhuashop 2
kehaishop 1
xiwangshop 1

t=int(input())
for T in range(t):
m, n = map(int, input().split())
zd = {}
s = map(str, input().split())
s = list(s)
book = {}
book1 = {}  # 按列输入书
for M in range(m):
zd[s[M]] = 0
d = map(float, input().split())
d = list(d)
book[M] = d  # 直接把一行书都读入
# print(book)
for N in range(n):  # 列
book1[N] = []
for M in range(m):  # 行
book1[N].append(book[M][N])
# print(book1)
zd = {}
for M in range(m):
# print(s[M])
zd[s[M]] = 0
for N in range(n):
# print(book[M][N])
# print(min(book1[N]))
if book[M][N] == min(book1[N]):
zd[s[M]] += 1
# print(zd)
zdt = sorted(zd.items(), key=lambda x: (-x[1], x[0]))
# print(zdt)
for i in range(m):
print("{} {}".format(zdt[i][0], zdt[i][1]))
"""3 3
xiwangshop kehaishop xinhuashop
11.1 22.2 33.3
11.2 22.2 33.2
10.9 22.3 33.1"""


## 7-20 三维向量运算 (20 分)

(4, 6, 8)
(4, 6, 8)
(-2, -2, -2)
(3, 6, 9)
(1.5, 2.0, 2.5)
(1, 2, 2)

print("(4, 6, 8)\n(4, 6, 8)\n(-2, -2, -2)\n(3, 6, 9)\n(1.5, 2.0, 2.5)\n(1, 2, 2)")
#之后想一下重载加号，减号https://zhidao.baidu.com/question/186652354.html



## 7-21 有关队列操作 (20 分)

9
1 23
1 34
3
4
2
1 56
2
3
1 90

2
23 34
23
34
1


class MyQueue:
queuen=[]
length=0
def _init_(self,length,queuen):
self.queuen=[]
self.length=0
def push(self,x):
self.queuen.append(x)
self.length+=1
def pop(self):
if self.length==0:
print("Invalid")
else:
self.queuen.reverse()
tmp=self.queuen.pop()
self.queuen.reverse()
self.length-=1
print(tmp)
return tmp
def size(self):
print(self.length)
return self.length
def show(self):
for i in range(self.length):
if i!=self.length-1:
print("{} ".format(self.queuen[i]),end="")
else:
print("{}".format(self.queuen[i]))
n=int(input())
q=MyQueue()
for N in range(n):
m=map(int,input().split())
m=list(m)
if len(m)==2:
q.push(m[1])
else:
if m[0]==2:
q.pop()
elif m[0]==3:
q.size()
elif m[0]==4:
q.show()


## 7-23 sdut-oop-5 计算长方体和四棱锥的表面积和体积（类的继承） (10 分)

008.jpg

（1）在父类Rect中，定义求底面周长的方法length( )和底面积的方法area( )。

（2）定义父类Rect的子类立方体类Cubic，计算立方体的表面积和体积。其中表面积area( )重写父类的方法。

（3）定义父类Rect的子类四棱锥类Pyramid，计算四棱锥的表面积和体积。其中表面积area( )重写父类的方法。

（4）在主程序中，输入立体图形的长(l)、宽(h)、高(z)数据，分别输出长方体的表面积、体积、四棱锥的表面积和体积。

（1）四棱锥体积公式：V=
3
1

Sh，S——底面积 h——高

（2）在Java中，利用Math.sqrt(a)方法可以求得a的平方根（方法的参数及返回结果均为double数据类型）

（3）在Python中，利用math模块的sqrt(a)方法，求得a的平方根。

1 2 3
0 2 3
-1 2 3
3 4 5

22.00 6.00 11.25 2.00
0.00 0.00 0.00 0.00
0.00 0.00 0.00 0.00
94.00 60.00 49.04 20.00

import math as m
class Rect:
def __init__(self,l,h,z):
self.l=l
self.h=h
self.z=z
def length(self):
return 2*(self.l+self.h)
def area(self):
return l*h
class Cubic(Rect):
def __init__(self, l, h, z):
super(Cubic, self).__init__(l, h, z)
def v(self):
return self.l*self.h*self.z
def area(self):
return 2*(self.l*self.h+self.l*self.z+self.z*self.h)
class Pyramid(Rect):
def __init__(self, l, h, z):
super(Pyramid, self).__init__(l, h, z)
def v(self):
return l*z*h/3
def area(self):
return m.sqrt(self.h*self.h+4*self.z*self.z)*self.l/2+self.h*self.l+m.sqrt(self.l*self.l+4*self.z*self.z)*self.h/2
while True:
try:
l, h, z = map(float, input().split())
for i in range(4):
if l<=0 or h<=0 or z<=0:
print("0.00 0.00 0.00 0.00")
break
else:
if i==0:
cbmj=Cubic(l,h,z)
print("%.2f"%cbmj.area(),end=" ")
elif i==1:
ctj=Cubic(l,h,z)
print("%.2f"%ctj.v(),end=" ")
elif i==2:
sbmj=Pyramid(l,h,z)
print("%.2f"%sbmj.area(),end=" ")
elif i==3:
stj=Pyramid(l,h,z)
print("%.2f"%stj.v())
except:
break


## 7-24 sdut-Time类的定义与使用 (10 分)

setHour(int)设置数据成员hour的值（采用12小时制），非法的输入默认为12；
setMinue(int)设置数据成员minute的值，非法输入默认为0；
setSecond(int)设置数据成员second的值，非法输入默认为0；
setTime(int，int，int)设置时、分、秒三个数据成员的值；
showTime()显示时间对象的值。

10 11 12

10:11:12

58 23 85

12:23:00

class Time:
def __init__(self,hour,minute,second):
self.hour=0
self.minute=0
self.second=0

def setHour(self, hour):
if hour < 0 or hour > 12:
self.hour = 12
else:
self.hour = hour

def setMinue(self, minute):
if minute > 60 or minute < 0:
self.minute = 0
else:
self.minute = minute

def setSecond(self, second):
if second > 60 or second < 0:
self.second = 0
else:
self._second = second
def setTime(self,hour,minute,second):
if hour < 0 or hour > 12:#我想在函数内部调用上面的函数，但是没有成功，以及私有变量不会用，老是报错
self.hour = 12
else:
self.hour = hour
if minute > 60 or minute < 0:
self.minute = 0
else:
self.minute = minute
if second > 60 or second < 0:
self.second = 0
else:
self.second = second
def showTime(self):
print("{:02d}:{:02d}:{:02d}".format((self.hour),(self.minute),(self.second)))
# print(self.hour)
# print(self.second)
# print(self.minute)
h,m,s=map(int,input().split())
mt=Time(h,m,s)
mt.setHour(h)
mt.setMinue(m)
mt.setSecond(s)
mt.setTime(h,m,s)
mt.showTime()



## 7-25 新型计算器 (20 分)

1、定义类名为 VecCal，设计构造函数创建三维向量对象： def init(self, x=0,y=0,z=0) 用x,y,z指代三个维度的值

2、重写加法（+），减法（-），乘法（ ）和整除除法（//）运算，实现向量的加减乘除*

3、除法运算作异常处理，当输入标量数字是0时，除法结果为 （0，0，0）

def add(self, n): # 加法
result = VecCal() # 定义结果变量，也是一个三维向量，通过构造函数创建
result.X = self.X + n.X
result.Y = self.Y + n.Y
result.Z = self.Z + n.Z
return result # 返回 执行加法运算后的向量结果

(1, 2, 3) + (4, 5, 6) = (5, 7, 9)

(1, 2, 3) - (4, 5, 6) = (-3, -3, -3)

(1, 2, 3) * 3 = (3, 6, 9)

(1, 2, 3) / 3 = (0, 0, 1)

1,2,3
4,5,6
3

(1, 2, 3) + (4, 5, 6) = (5, 7, 9)
(1, 2, 3) - (4, 5, 6) = (-3, -3, -3)
(1, 2, 3) * 3 = (3, 6, 9)
(1, 2, 3) / 3 = (0, 0, 1)

a,b,c=map(int,input().split(","))
t,y,x=map(int,input().split(","))
chu=int(input())
print("({}, {}, {}) + ({}, {}, {}) = ({}, {}, {})".format(a,b,c,t,y,x,a+t,b+y,c+x))
print("({}, {}, {}) - ({}, {}, {}) = ({}, {}, {})".format(a,b,c,t,y,x,a-t,b-y,c-x))
print("({}, {}, {}) * {} = ({}, {}, {})".format(a,b,c,chu,a*chu,b*chu,c*chu))
if chu==0:
print("({}, {}, {}) / {} = ({}, {}, {})".format(a,b,c,chu,0,0,0))
else:
print("({}, {}, {}) / {} = ({}, {}, {})".format(a,b,c,chu,a//chu,b//chu,c//chu))

• 32
点赞
• 133
收藏
觉得还不错? 一键收藏
• 打赏
• 4
评论
06-19 4067
03-20 8660
05-23 2292
03-28 160
11-15 1万+
01-25
12-10
12-07
02-25 1177

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

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

~晚风微凉~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20

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