浙大版PTA《Python 程序设计》题目集 参考答案

本答案配套详解教程专栏,欢迎订阅:

PTA浙大版《Python 程序设计》题目集 详解教程_少侠PSY的博客-CSDN博客

01第1章-1 从键盘输入两个数,求它们的和并输出

a=int(input()) # 输入a的值b=int(input()) # 输入b的值print(a+b) # 输出a+b的值

02第1章-2 从键盘输入三个数到a,b,c中,按公式值输出

a,b,c=input().split()a=int(a)b=int(b)c=int(c)print(b*b-4*a*c)

03第1章-3 输出“人生苦短,我学Python”

print("人生苦短,我学Python")

04第2章-1 计算 11+12+13+…+m

m=int(input())s=sum([i for i in range(11,m+1)])print("sum =",s)

05第2章-2 计算分段函数[1]

x = float(input())if x != 0:y = 1 / xelse:y = 0print("f({:.1f}) = {:.1f}".format(x, y))

06第2章-3 阶梯电价

e = float(input())cost = 0if e < 0:print("Invalid Value!")else:if e <= 50.00:cost = e * 0.53else:cost = 50.0 * 0.53 + (e - 50) * (0.53 + 0.05)print(f"cost = {cost:.2f}")

07第2章-4 特殊a串数列求和

a, n = map(int, input().split())tn = 0sn = 0for i in range(1, n + 1):tn = tn * 10 + a #第n项的值sn = sn + tn #前n项的和print("s =", sn)

08第2章-5 求奇数分之一序列前N项和

N = int(input())s = 0for i in range(N):s += 1 / (i + i + 1)print(f"sum = {s:.6f}")

09第2章-6 求交错序列前N项和

n = int(input())sum = 0sign = 1for i in range(1, n + 1):sum += sign * i / (i + i - 1)sign *= -1print(f"{sum:.3f}")

10第2章-7 产生每位数字相同的n位数

a,b=input().split(',')print(int(str(int(a))*int(b)))

11第2章-8 转换函数使用

x,y=eval(input()) # x,y=map(int, input().split(','))print(int(str(x),y)) 

12第2章-9 比较大小

a, b, c = map(int, input().split())if b > c:b, c = c, b if a > b:a, b = b, a if b > c:b, c = c, bprint(f"{a}->{b}->{c}")

13第2章-10 输出华氏-摄氏温度转换表

lower, upper = map(int, input().split())if lower > upper:print("Invalid.")else:print("fahr celsius")while lower <= upper:celsius = 5 * (lower - 32) / 9print(f"{lower:d}{celsius:6.1f}")lower += 2

14第2章-11 求平方与倒数序列的部分和

m, n = map(int, input().split())res = 0for i in range(m, n + 1):res += i * i + 1 / iprint(f"sum = {res:.6f}")

15第2章-12 输出三角形面积和周长

import matha, b, c = map(int, input().split())if a + b > c and b + c > a and a + c > b:perimeter = a + b + cs = (a + b + c) / 2.0area = math.sqrt(s * (s - a) * (s - b) * (s - c))print(f"area = {area:.2f}; perimeter = {perimeter:.2f}")else:print("These sides do not correspond to a valid triangle")

16第2章-13 分段计算居民水费

x = float(input())if x > 15.0:print("{:.2f}".format(2.5 * x - 17.5))else:print("{:.2f}".format(4 * x / 3))

17第2章-14 求整数段和

A, B = map(int, input().split())s = c = 0for i in range(A, B + 1):print(f'{i:5d}', end='')c += 1if c == 5:print()c = 0s += iif c:print()print(f'Sum = {s}')

18第3章-1 大于身高的平均值

l=input().split()l1=[int(i) for i in l]aver=sum(l1)/len(l1)l2=[i for i in l1 if i>aver]for i in l2: print(i,end=' ')

19第3章-2 查验身份证

#自定义函数,用于验证一个身份证号码是否合法。def validate_id_number(s):w = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]m = "10X98765432"sum = 0for j in range(17):if not s[j].isdigit():return Falsesum += int(s[j]) * w[j]sum = sum % 11if s[17] != m[sum]:return Falsereturn True# 主程序n = int(input())cnt = 0for i in range(n):s = input()if len(s) != 18 or not validate_id_number(s):cnt += 1print(s)if cnt == 0:print("All passed")

20第3章-3 输出字母在字符串中位置索引

sen=input()a,b=input().split()lst=[(i,sen[i]) for i in range(len(sen)) if sen[i]==a or sen[i]==b]lstnew=lst[::-1]for i in range(len(lstnew)):print(lstnew[i][0],lstnew[i][1])

21第3章-4 查找指定字符

cc = input()str = input()index = -1for i in range(len(str)):if str[i] == cc:index = iif index != -1:print(f"index = {index}")else:print("Not Found")

22第3章-5 字符转换

s = input()n = 0for char in s:if '0' <= char <= '9':n = n * 10 + int(char)print(n)

23第3章-6 求整数序列中出现次数最多的数

a = input().split()element_count = {} if a:a.pop(0)for element in a:element_count[element] = a.count(element)max_element = max(element_count, key=element_count.get) max_count = element_count[max_element]print(max_element, max_count)

24第3章-7 求最大值及其下标

n=int(input())a=list(map(int,input().split()))print(max(a),a.index(max(a)))

25第3章-8 字符串逆序

s = input()s = s[::-1]print(s)

26第3章-9 字符串转换成十进制整数

s = input()hex_str = "" negative = False for c in s:if c.isdigit() or c.upper() in "ABCDEF":hex_str += celif c == "-" and len(hex_str) == 0:negative = Trueif hex_str:num = int(hex_str, 16)if negative:num = -numprint(num)else:print(0)

27第3章-10 统计大写辅音字母

a = input()cnt=0for n in a : if n.isupper() and n!="A" and n!="E" and n!="I" and n!="O" and n!="U":cnt=cnt+1print(cnt)

28第3章-11 字符串排序

lst = input().split()lst.sort()print("After sorted:")for i in range(0,len(lst)):print(lst[i])

29第3章-12 求整数的位数及各位数字之和

n=input()l=[int(i) for i in n]print(len(n),sum(l))

30第3章-13 字符串替换

a = list(input())m = [chr(i) for i in range(ord('A'),ord('Z')+1)]for i in range(len(a)):if a[i] in m:b=m.index(a[i])a[i]=m[25-b]b="".join(a)print(b)

31第3章-14 字符串字母大小写转换

str = input()for i in str:if i == "#":breakelif i.islower():print(i.upper(),end = "")elif i.isupper():print(i.lower(),end = "")else:print(i,end = "")

32第3章-15 统计一行文本的单词个数

cnt=0for i in input().split():cnt+=1print(cnt)

33第3章-16 删除重复字符

a=set(input())lst=list(a)lst.sort()print(f"{''.join(lst)}")

34第3章-17 删除字符

str=input()c=input()str,c=str.strip(),c.strip()#移除字符串两端的空白字符result=str.replace(c.upper(),"")#将 c 的大写形式删除result=result.replace(c.lower(),"")#将 c 的小写形式删除print("result:",result)

35第3章-18 输出10个不重复的英文字母

s = input().strip()li = []for i in s:if i.isalpha() and i.upper() not in li and i.lower() not in li :li.append(i)if len(li)==10:breakif len(li)<10:print('not found')else:s = ''.join(li)print(s)

36第3章-19 找最长的字符串

n = int(input())max = 0for i in range(n):s = input()if(max<len(s)):max=len(s)maxstr=sprint('The longest is:',maxstr)

37第3章-20 逆序的三位数

s=input()s=s[::-1]print(int(s))

38第3章-21 判断回文字符串

s=input()print(s)if s==s[::-1]:print('Yes')else:print('No')

39第3章-22 输出大写英文字母

s = input()t=""flag=0for element in s:if(element.isupper()):t=t+elementflag=1if(flag==0):print("Not Found")else:lst=list(t)res=list(set(lst))res.sort(key=lst.index)print("".join(res))

40第4章-1 生成3的乘方表

n=int(input())for i in range(n+1):a = 3**iprint(f"pow(3,{i}) = {a}")

41第4章-2 统计素数并求和

import mathdef is_prime(num):sqrt_num = int(math.sqrt(num))if num == 1:return Falsefor i in range(2, sqrt_num + 1):if num % i == 0:return Falsereturn Truem, n = map(int, input().split())counts = 0sum = 0for i in range(m, n+1):if is_prime(i):counts += 1sum += iprint(f"{counts} {sum}")

42第4章-3 猴子吃桃问题

N=int(input())def show(N):x=1for i in range(0,N-1):x=(x+1)*2return xprint(show(N))

43第4章-4 验证“哥德巴赫猜想”

import mathdef isPrime(num):sqrt_num = int(math.sqrt(num))if num == 1:return Falsefor i in range(2, sqrt_num + 1):if num % i == 0:return Falsereturn Truex=int(input())for y in range(2,x//2+1):z = x - yif (isPrime(y) == 1 and isPrime(z) == 1):print('{:d} = {:d} + {:d}'.format(x, y, z))break

44第4章-5 求e的近似值

from math import factorialtotal = 1n = int(input())for i in range(n):total += 1/factorial(i+1)print(f'{total:.8f}')

45第4章-6 输出前 n 个Fibonacci数

n=int(input())a, b = 0, 1if(n>0):for i in range(n):print(f'{b:11d}',end="")a, b = b, a + bif((i+1)%5==0):print()else:print("Invalid.")

46第4章-7 统计学生平均成绩与及格人数

n=int(input())if(n==0):print('average = 0.0')print('count = 0')else:lst = list(map(int,input().split()))sum = sum(lst)aver=sum/nnew_lst = [x for x in lst if x >= 60]cnt = len(new_lst)print(f'average = {aver:.1f}')print(f'count = {cnt:d}')

47第4章-8 求分数序列前N项和

N=int(input())a,b,c=2,1,0for i in range(N):c+=a/ba,b=a+b,aprint(f"{c:.2f}")

48第4章-9 查询水果价格

print("[1] apple\n[2] pear\n[3] orange\n[4] grape\n[0] exit")num=list(map(int,input().split()))price=[3,2.5,4.1,10.2]for i in range(len(num)):if num[i]==0 or i>=5:breakelif num[i]>0 and num[i]<5:print("price = %.2f"%price[num[i]-1])else:print("price = 0.00")

49第4章-10 最大公约数和最小公倍数

import matha,b=map(int,input().split())print(math.gcd(a,b),int((a*b)/math.gcd(a,b)))

50第4章-11 判断素数

def prime(n):if n < 2:return Falsefor i in range(2, int(n**0.5)+1):if n % i == 0:return Falsereturn Truen = int(input())for i in range(n):num = eval(input())print('Yes') if prime(num) else print('No')

51第4章-12 求满足条件的斐波那契数

n = int(input("请输入一个整数:"))fibonacci_sequence = [1, 1]while fibonacci_sequence[-1] < n:next_fib = fibonacci_sequence[-1] + fibonacci_sequence[-2]fibonacci_sequence.append(next_fib)print("最后一个小于", n, "的斐波那契数是:", fibonacci_sequence[-1])

52第4章-13 求误差小于输入值的e的近似值

a=float(input())b,c=2,1n,count=2,1while b-c>=a:count*=nn+=1c=bb=b+1/countprint(f"{b:.6f}")

53第4章-14 统计字符

input_string = input()letter_count, blank_count, digit_count, other_count = 0, 0, 0, 0while len(input_string) < 10:input_string += '\n'# 行尾回车符补上input_string += input()input_string = input_string[:10]for char in input_string:if char.isalpha():letter_count += 1elif char.isspace():blank_count += 1elif char.isdigit():digit_count += 1else:other_count += 1print('letter = {}, blank = {}, digit = {}, other = {}'.format(letter_count, blank_count, digit_count, other_count))

54第4章-15 换硬币

money = int(input())count = 0 #记录满足条件的组合方式的数量total = 0 #计算当前组合方式的硬币总数for fen5 in range(money // 5, 0, -1):for fen2 in range((money - fen5 * 5) // 2, 0, -1):fen1 = money - fen5 * 5 - fen2 * 2total = fen5 + fen2 + fen1if fen1 > 0:print(f"fen5:{fen5}, fen2:{fen2}, fen1:{fen1}, total:{total}")count += 1total = 0print(f"count = {count}")

55第4章-16 jmu-python-判断是否构成三角形

a,b,c=map(int,input().split())if a+b>c and a+c>b and b+c>a and a>0 and b>0 and c>0:print('yes')else:print('no')

56第4章-17 水仙花数

n = int(input())for i in range(10**(n-1), 10**n):#遍历ls = [int(x)**n for x in str(i)] #计算每个数字的n次方if sum(ls) == i: #每个位上的数字求和,然后与数本身进行比较print(i)

57第4章-18 猴子选大王

n=int(input())a=[i for i in range(1,n+1)]index=0while len(a)>1:x=a.pop(0)index+=1if index==3:index=0else:a.append(x)print(a[0])

58第4章-19 矩阵运算

n = int(input())total = 0matrix = []for i in range(n):row = list(map(int, input().split()))matrix.append(row)for i in range(n):for j in range(n):if i + j != n - 1 and j != n - 1 and i != n - 1:total += matrix[i][j]print(total)

59第4章-20 求矩阵各行元素之和

m,n=map(int,input().split())for i in range(m):sr=list(map(int,input().split()))print(sum(sr))

60第4章-21 判断上三角矩阵

T = int(input()) for _ in range(T): n = int(input())matrix = []for i in range(n):row = list(map(int, input().split()))matrix.append(row)upper_triangle = Truefor i in range(n):for j in range(n):if i > j and matrix[i][j] != 0:upper_triangle = False breakif upper_triangle: print("YES")else:print("NO")

61第4章-22 找鞍点

num = int(input())matrix = []for i in range(num):matrix.append(list(map(int, input().split())))for i in range(num):max_row = max(matrix[i][k] for k in range(num))for j in range(num):min_col = min(matrix[k][j] for k in range(num))if max_row == min_col:print(f"{i} {j}")exit()print("NONE")

62第4章-23 求矩阵的局部极大值

m,n=map(int,input().split())ls=[]count=0for i in range(m):s=input()ls.append([int(i) for i in s.split()])for i in range(1,m-1):for j in range(1,n-1):if ls[i][j]>ls[i-1][j] and ls[i][j]>ls[i+1][j] and ls[i][j]>ls[i][j-1] and ls[i][j]>ls[i][j+1]:print(ls[i][j],i+1,j+1)count+=1if count==0:print("None",m,n)

63第4章-24 打印九九口诀表

n=int(input())for i in range(1,n+1):for j in range(1,i+1):print("%d*%d=%-4d"%(j,i,i*j),end='')print()

64第4章-25 输出三角形字符阵列

n=int(input())s=ord("A")for i in range(n,0,-1):for j in range(i):print(chr(s),end=' ')s +=1print()

65第4章-26 求1!+3!+5!+……+n!

n = int(input())total_sum = 1factorial = 1for odd_number in range(3, n + 1, 2):factorial *= odd_number*(odd_number-1)total_sum += factorialprint(f"n={n},s={total_sum}")

66第4章-27 二维数组中每行最大值和每行和

ls=list(map(int,input().split()))s=[]for j in range(3):s=ls[3*j:(j+1)*3]for i in range(3):print("{:>4d}".format(s[i]),end='')print(f"{max(s):>4d}",end='')print(f"{sum(s):>4d}")

67第4章-28 矩阵转置第4章-28 矩阵转置

ls=list(map(int,input().split()))s=[]for i in range(3):s.append(ls[3*i:(i+1)*3])for i in range(3):for j in range(3):print(f"{s[j][i]:>4d}",end='')print()

68第4章-29 找出不是两个数组共有的元素

l1=list(map(str,input().split()))l2=list(map(str,input().split()))ls=[]l1.pop(0)l2.pop(0)for i in l1:if i not in l2 and i not in ls:ls.append(i)for j in l2:if j not in l1 and j not in ls:ls.append(j)print(*ls)

69第4章-30 找完数

flag = 0m,n = map(int,input().split())for i in range (m,n+1):s = [1] for j in range (2,int(i**0.5 + 1)):if i%j ==0:s.append(j)s.append(i//j)if sum(s) == i:s.sort()print (i,end=" = ")print(' + '.join(map(str,s)))flag=1if(flag == 0):print("None")

70第5章-1 输出星期名缩写

a=input()sum={'1':'Mon','2':'Tue','3':'Wed','4':'Thu','5':'Fri','6':'Sat','7':'Sun'}print(sum[a])

71第5章-2 图的字典表示

n=int(input())vertex=0edge=0length=0for i in range(n):l=input()d=eval(l)for key1 in d:vertex+=1for key2 in d[key1]:edge+=1length+=d[key1][key2]print(vertex,edge,length)

72第5章-3 四则运算(用字典实现)

result={"+":"x+y","-":"x-y","*":"x*y","/":'x/y if y!=0 \else "divided by zero"'}x=int(input())z=input()y=int(input())r=eval(result.get(z))if type(r)!=str: print(f'{r:.2f}') else: print(r)

73第5章-4 分析活动投票情况

s={"6","7","8","9","10"}-set(input().split(","))lst=list(s)lst=[int(i) for i in lst]lst.sort()print(*lst)

74第5章-5 统计字符出现次数

s=input()ch=input()dc={}for c in s:dc[c]=dc.get(c,0)+1if ch in s:print(dc[ch])else:print(0)

75第5章-6 统计工龄

N = int(input())dic = {}ls = list(map(int,input().split()))for i in ls:if i not in dic:dic[i] = 1else:dic[i]+=1for i in sorted(dic.keys()):print(f"{i}:{dic[i]}")

76第5章-7 列表去重

lst=eval(input())seen=set()lst1=[i for i in lst if i not in seen and not seen.add(i)]print(*lst1)

77第5章-8 能被3,5和7整除的数的个数(用集合实现)

a,b=input().split()a,b=int(a),int(b)s1=set([i for i in range(a,b+1) if i%3==0])s2=set([i for i in range(a,b+1) if i%5==0])s3=set([i for i in range(a,b+1) if i%7==0])print(len(s1&s2&s3))

78第5章-9 求矩阵鞍点的个数

n=int(input())a=[]for i in range(0,n):b=input().split()a.insert(i,b)c=[]d=[]for i in range(0,n):maxa=max(int(a[i][j]) for j in range(n))mina=min(int(a[k][i]) for k in range(0,n))c+=[(i,j) for j in range(n) if int(a[i][j])==maxa]d+=[(k,i) for k in range(n) if int(a[k][i])==mina]c=list(set(c)&set(d))print(len(c))

79第5章-10 两数之和

nums = list(map(int,input().split(',')))target = int(input())hm = dict()for i in range(len(nums)):if nums[i] in hm:print(hm[nums[i]], i)breakhm[target - nums[i]] = ielse:print("no answer")

80第5章-11 字典合并

#合并字典dic1=eval(input())dic2=eval(input())dic3={}keys=set(dic1.keys())|set(dic2.keys())for key in keys:value=dic1.get(key,0)+dic2.get(key,0)dic3[key]=value#排序lst=[(ord(k) if k not in range(0,10) else k,v) for k,v in dic3.items()]lst.sort()#输出lst1=[]for t in lst:if 0<=t[0]<=9:lst1.append("{}:{}".format(t[0],t[1]))else:lst1.append('"{}":{}'.format(chr(t[0]),t[1]))print("{"+",".join(lst1)+"}")

81第6章-1 输入列表,求列表元素和(eval输入应用)

lst=eval(input())s=sum([i for i in lst]) print(s)

82第6章-2 一帮一

N = int(input())male_students = []# 存储男生信息的列表female_students = []# 存储女生信息的列表count = 1while N > 0:s = list(input().split())if int(s[0]) == 1:male_students.append([s[1], count])count+=1else:female_students.append([s[1], count])count += 1N -= 1while male_students and female_students:if male_students[0][1] < female_students[0][1]:print(f"{male_students.pop(0)[0]} {female_students.pop()[0]}")else:print(f"{female_students.pop(0)[0]} {male_students.pop()[0]}")

83第6章-3 列表或元组的数字元素求和

def sum_nested_numbers(data):total = 0for item in data:if isinstance(item, (int, float)):total += itemelif isinstance(item, (list, tuple)):total += sum_nested_numbers(item)return totalinput_data = eval(input())# 从输入字符串中解析出列表或元组result = sum_nested_numbers(input_data)print(result)

84第6章-4 列表数字元素加权和(1)

def calculate_weighted_sum(lst, depth=1):total = 0for item in lst:if isinstance(item, list):total += calculate_weighted_sum(item, depth + 1)else:total += item * depthreturn totalinput_list = eval(input())result = calculate_weighted_sum(input_list)print(result)

85第6章-5 列表元素个数的加权和(1)

def weighted_element_count(lst, depth=1):count = 0for item in lst:if isinstance(item, list):count += weighted_element_count(item, depth + 1)else:count += depthreturn countinput_str = input()input_list = eval(input_str)result = weighted_element_count(input_list)print(result)

86第6章-6 求指定层的元素个数

def count_integers_at_depth(X, depth):cnt = 0for x in X:if type(x)==int:if depth == n:cnt += 1else:cnt += count_integers_at_depth(x, depth + 1)return cntX = eval(input())n = int(input())print(count_integers_at_depth(X, 1))

87第6章-7 找出总分最高的学生

num_students = int(input())student_info = {}max_total_score = -1for i in range(num_students):info = input().split()student_id = info[0]student_name = info[1]scores = list(map(int, info[2:]))total_score = sum(scores)if total_score > max_total_score:max_total_score = total_scoretop_student = (student_name, student_id, total_score)print("{} {} {}".format(top_student[0], top_student[1], top_student[2]))

88第6章-8 输出全排列

import itertoolsn = int(input())numbers = list(range(1, n + 1))permutations = list(itertools.permutations(numbers))for perm in permutations:print("".join(map(str, perm)))

89 第6章函数-1

def fn(a, n):result = 0current_term = 0for i in range(1, n + 1):current_term = current_term * 10 + aresult += current_termreturn result

90第6章函数-2 使用函数求素数和

# 定义一个函数 prime,用于判断一个数是否为素数def prime(p):if p <= 1:return Falsefor i in range(2, int(p**0.5) + 1):if p % i == 0:return Falsereturn True# 定义函数 PrimeSum,用于返回区间 [m, n] 内所有素数的和def PrimeSum(m, n):prime_sum = 0for num in range(m, n + 1):if prime(num):prime_sum += numreturn prime_sum

91第6章函数-3 使用函数统计指定数字的个数

def CountDigit(number,digit ): numlist=list(str(number)) dig=str(digit) count=numlist.count(dig) return count

92第6章函数-4 使用函数输出指定范围内Fibonacci数的个数

def fib(n):if n==0:return 1elif n==1:return 1 else:i=2;a=1;b=1while i<=n: a,b = b,a+b i=i+1return bdef PrintFN(m,n): fiblist=[] a=1;b=1 while a<=n: if a>=m:fiblist.append(a) a,b=b,a+b return fiblist

93第6章函数-5 使用函数求余弦函数的近似值

import mathdef funcos(eps,x):i=0;s=0;flag=1while True: item=x**i/math.factorial(i) if abs(item)>=eps: s=s+flag*item flag=-flag i=i+2 else: breakreturn s

94第6章函数-6 缩写词

defacronym(phrase):words=phrase.split()res=""for word in words: res=res+word[0].upper()return res

95第7章-1 词频统计

import re, collections, syswords = "".join([line for line in sys.stdin])words = re.compile(r"\w+", re.I).findall(words.lower().split('#')[0])words = [each.strip() for each in words]words = list(map(lambda each: each[0:15] if len(each) > 15 else each, words))counter = collections.Counter(words)rank = sorted(counter.items(), key=lambda each: (-each[1], each[0]), reverse=False)print(len(rank))for each in rank[0:int(0.1*len(rank))]:print("{}:{}".format(each[1], each[0]))