本答案配套详解教程专栏,欢迎订阅:
PTA浙大版《Python 程序设计》题目集 详解教程_少侠PSY的博客-CSDN博客
a=int(input()) # 输入a的值
b=int(input()) # 输入b的值
print(a+b) # 输出a+b的值
a,b,c=input().split()
a=int(a)
b=int(b)
c=int(c)
print(b*b-4*a*c)
print("人生苦短,我学Python")
m=int(input())
s=sum([i for i in range(11,m+1)])
print("sum =",s)
x = float(input())
if x != 0:
y = 1 / x
else:
y = 0
print("f({:.1f}) = {:.1f}".format(x, y))
e = float(input())
cost = 0
if e < 0:
print("Invalid Value!")
else:
if e <= 50.00:
cost = e * 0.53
else:
cost = 50.0 * 0.53 + (e - 50) * (0.53 + 0.05)
print(f"cost = {cost:.2f}")
a, n = map(int, input().split())
tn = 0
sn = 0
for i in range(1, n + 1):
tn = tn * 10 + a #第n项的值
sn = sn + tn #前n项的和
print("s =", sn)
N = int(input())
s = 0
for i in range(N):
s += 1 / (i + i + 1)
print(f"sum = {s:.6f}")
n = int(input())
sum = 0
sign = 1
for i in range(1, n + 1):
sum += sign * i / (i + i - 1)
sign *= -1
print(f"{sum:.3f}")
a,b=input().split(',')
print(int(str(int(a))*int(b)))
x,y=eval(input()) # x,y=map(int, input().split(','))
print(int(str(x),y))
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, b
print(f"{a}->{b}->{c}")
lower, upper = map(int, input().split())
if lower > upper:
print("Invalid.")
else:
print("fahr celsius")
while lower <= upper:
celsius = 5 * (lower - 32) / 9
print(f"{lower:d}{celsius:6.1f}")
lower += 2
m, n = map(int, input().split())
res = 0
for i in range(m, n + 1):
res += i * i + 1 / i
print(f"sum = {res:.6f}")
import math
a, b, c = map(int, input().split())
if a + b > c and b + c > a and a + c > b:
perimeter = a + b + c
s = (a + b + c) / 2.0
area = 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")
x = float(input())
if x > 15.0:
print("{:.2f}".format(2.5 * x - 17.5))
else:
print("{:.2f}".format(4 * x / 3))
A, B = map(int, input().split())
s = c = 0
for i in range(A, B + 1):
print(f'{i:5d}', end='')
c += 1
if c == 5:
print()
c = 0
s += i
if c:
print()
print(f'Sum = {s}')
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=' ')
#自定义函数,用于验证一个身份证号码是否合法。
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 = 0
for j in range(17):
if not s[j].isdigit():
return False
sum += int(s[j]) * w[j]
sum = sum % 11
if s[17] != m[sum]:
return False
return True
# 主程序
n = int(input())
cnt = 0
for i in range(n):
s = input()
if len(s) != 18 or not validate_id_number(s):
cnt += 1
print(s)
if cnt == 0:
print("All passed")
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])
cc = input()
str = input()
index = -1
for i in range(len(str)):
if str[i] == cc:
index = i
if index != -1:
print(f"index = {index}")
else:
print("Not Found")
s = input()
n = 0
for char in s:
if '0' <= char <= '9':
n = n * 10 + int(char)
print(n)
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)
n=int(input())
a=list(map(int,input().split()))
print(max(a),a.index(max(a)))
s = input()
s = s[::-1]
print(s)
s = input()
hex_str = ""
negative = False
for c in s:
if c.isdigit() or c.upper() in "ABCDEF":
hex_str += c
elif c == "-" and len(hex_str) == 0:
negative = True
if hex_str:
num = int(hex_str, 16)
if negative:
num = -num
print(num)
else:
print(0)
a = input()
cnt=0
for n in a :
if n.isupper() and n!="A" and n!="E" and n!="I" and n!="O" and n!="U":
cnt=cnt+1
print(cnt)
lst = input().split()
lst.sort()
print("After sorted:")
for i in range(0,len(lst)):
print(lst[i])
n=input()
l=[int(i) for i in n]
print(len(n),sum(l))
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)
str = input()
for i in str:
if i == "#":
break
elif i.islower():
print(i.upper(),end = "")
elif i.isupper():
print(i.lower(),end = "")
else:
print(i,end = "")
cnt=0
for i in input().split():
cnt+=1
print(cnt)
a=set(input())
lst=list(a)
lst.sort()
print(f"{''.join(lst)}")
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)
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:
break
if len(li)<10:
print('not found')
else:
s = ''.join(li)
print(s)
n = int(input())
max = 0
for i in range(n):
s = input()
if(max<len(s)):
max=len(s)
maxstr=s
print('The longest is:',maxstr)
s=input()
s=s[::-1]
print(int(s))
s=input()
print(s)
if s==s[::-1]:
print('Yes')
else:
print('No')
s = input()
t=""
flag=0
for element in s:
if(element.isupper()):
t=t+element
flag=1
if(flag==0):
print("Not Found")
else:
lst=list(t)
res=list(set(lst))
res.sort(key=lst.index)
print("".join(res))
n=int(input())
for i in range(n+1):
a = 3**i
print(f"pow(3,{i}) = {a}")
import math
def is_prime(num):
sqrt_num = int(math.sqrt(num))
if num == 1:
return False
for i in range(2, sqrt_num + 1):
if num % i == 0:
return False
return True
m, n = map(int, input().split())
counts = 0
sum = 0
for i in range(m, n+1):
if is_prime(i):
counts += 1
sum += i
print(f"{counts} {sum}")
N=int(input())
def show(N):
x=1
for i in range(0,N-1):
x=(x+1)*2
return x
print(show(N))
import math
def isPrime(num):
sqrt_num = int(math.sqrt(num))
if num == 1:
return False
for i in range(2, sqrt_num + 1):
if num % i == 0:
return False
return True
x=int(input())
for y in range(2,x//2+1):
z = x - y
if (isPrime(y) == 1 and isPrime(z) == 1):
print('{:d} = {:d} + {:d}'.format(x, y, z))
break
from math import factorial
total = 1
n = int(input())
for i in range(n):
total += 1/factorial(i+1)
print(f'{total:.8f}')
n=int(input())
a, b = 0, 1
if(n>0):
for i in range(n):
print(f'{b:11d}',end="")
a, b = b, a + b
if((i+1)%5==0):
print()
else:
print("Invalid.")
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/n
new_lst = [x for x in lst if x >= 60]
cnt = len(new_lst)
print(f'average = {aver:.1f}')
print(f'count = {cnt:d}')
N=int(input())
a,b,c=2,1,0
for i in range(N):
c+=a/b
a,b=a+b,a
print(f"{c:.2f}")
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:
break
elif num[i]>0 and num[i]<5:
print("price = %.2f"%price[num[i]-1])
else:
print("price = 0.00")
import math
a,b=map(int,input().split())
print(math.gcd(a,b),int((a*b)/math.gcd(a,b)))
def prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
n = int(input())
for i in range(n):
num = eval(input())
print('Yes') if prime(num) else print('No')
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])
a=float(input())
b,c=2,1
n,count=2,1
while b-c>=a:
count*=n
n+=1
c=b
b=b+1/count
print(f"{b:.6f}")
input_string = input()
letter_count, blank_count, digit_count, other_count = 0, 0, 0, 0
while 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 += 1
elif char.isspace():
blank_count += 1
elif char.isdigit():
digit_count += 1
else:
other_count += 1
print('letter = {}, blank = {}, digit = {}, other = {}'.format(letter_count, blank_count, digit_count, other_count))
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 * 2
total = fen5 + fen2 + fen1
if fen1 > 0:
print(f"fen5:{fen5}, fen2:{fen2}, fen1:{fen1}, total:{total}")
count += 1
total = 0
print(f"count = {count}")
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')
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)
n=int(input())
a=[i for i in range(1,n+1)]
index=0
while len(a)>1:
x=a.pop(0)
index+=1
if index==3:
index=0
else:
a.append(x)
print(a[0])
n = int(input())
total = 0
matrix = []
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)
m,n=map(int,input().split())
for i in range(m):
sr=list(map(int,input().split()))
print(sum(sr))
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 = True
for i in range(n):
for j in range(n):
if i > j and matrix[i][j] != 0:
upper_triangle = False
break
if upper_triangle:
print("YES")
else:
print("NO")
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")
m,n=map(int,input().split())
ls=[]
count=0
for 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+=1
if count==0:
print("None",m,n)
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()
n=int(input())
s=ord("A")
for i in range(n,0,-1):
for j in range(i):
print(chr(s),end=' ')
s +=1
print()
n = int(input())
total_sum = 1
factorial = 1
for odd_number in range(3, n + 1, 2):
factorial *= odd_number*(odd_number-1)
total_sum += factorial
print(f"n={n},s={total_sum}")
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}")
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()
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)
flag = 0
m,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=1
if(flag == 0):
print("None")
a=input()
sum={'1':'Mon','2':'Tue','3':'Wed','4':'Thu','5':'Fri','6':'Sat','7':'Sun'}
print(sum[a])
n=int(input())
vertex=0
edge=0
length=0
for i in range(n):
l=input()
d=eval(l)
for key1 in d:
vertex+=1
for key2 in d[key1]:
edge+=1
length+=d[key1][key2]
print(vertex,edge,length)
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)
s={"6","7","8","9","10"}-set(input().split(","))
lst=list(s)
lst=[int(i) for i in lst]
lst.sort()
print(*lst)
s=input()
ch=input()
dc={}
for c in s:
dc[c]=dc.get(c,0)+1
if ch in s:
print(dc[ch])
else:
print(0)
N = int(input())
dic = {}
ls = list(map(int,input().split()))
for i in ls:
if i not in dic:
dic[i] = 1
else:
dic[i]+=1
for i in sorted(dic.keys()):
print(f"{i}:{dic[i]}")
lst=eval(input())
seen=set()
lst1=[i for i in lst if i not in seen and not seen.add(i)]
print(*lst1)
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))
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))
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)
break
hm[target - nums[i]] = i
else:
print("no answer")
#合并字典
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)+"}")
eval
输入应用)lst=eval(input())
s=sum([i for i in lst])
print(s)
N = int(input())
male_students = [] # 存储男生信息的列表
female_students = [] # 存储女生信息的列表
count = 1
while N > 0:
s = list(input().split())
if int(s[0]) == 1:
male_students.append([s[1], count])
count+=1
else:
female_students.append([s[1], count])
count += 1
N -= 1
while 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]}")
def sum_nested_numbers(data):
total = 0
for item in data:
if isinstance(item, (int, float)):
total += item
elif isinstance(item, (list, tuple)):
total += sum_nested_numbers(item)
return total
input_data = eval(input()) # 从输入字符串中解析出列表或元组
result = sum_nested_numbers(input_data)
print(result)
def calculate_weighted_sum(lst, depth=1):
total = 0
for item in lst:
if isinstance(item, list):
total += calculate_weighted_sum(item, depth + 1)
else:
total += item * depth
return total
input_list = eval(input())
result = calculate_weighted_sum(input_list)
print(result)
def weighted_element_count(lst, depth=1):
count = 0
for item in lst:
if isinstance(item, list):
count += weighted_element_count(item, depth + 1)
else:
count += depth
return count
input_str = input()
input_list = eval(input_str)
result = weighted_element_count(input_list)
print(result)
def count_integers_at_depth(X, depth):
cnt = 0
for x in X:
if type(x)==int:
if depth == n:
cnt += 1
else:
cnt += count_integers_at_depth(x, depth + 1)
return cnt
X = eval(input())
n = int(input())
print(count_integers_at_depth(X, 1))
num_students = int(input())
student_info = {}
max_total_score = -1
for 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_score
top_student = (student_name, student_id, total_score)
print("{} {} {}".format(top_student[0], top_student[1], top_student[2]))
import itertools
n = int(input())
numbers = list(range(1, n + 1))
permutations = list(itertools.permutations(numbers))
for perm in permutations:
print("".join(map(str, perm)))
def fn(a, n):
result = 0
current_term = 0
for i in range(1, n + 1):
current_term = current_term * 10 + a
result += current_term
return result
# 定义一个函数 prime,用于判断一个数是否为素数
def prime(p):
if p <= 1:
return False
for i in range(2, int(p**0.5) + 1):
if p % i == 0:
return False
return True
# 定义函数 PrimeSum,用于返回区间 [m, n] 内所有素数的和
def PrimeSum(m, n):
prime_sum = 0
for num in range(m, n + 1):
if prime(num):
prime_sum += num
return prime_sum
def CountDigit(number,digit ):
numlist=list(str(number))
dig=str(digit)
count=numlist.count(dig)
return count
def fib(n):
if n==0:
return 1
elif n==1:
return 1
else:
i=2;a=1;b=1
while i<=n:
a,b = b,a+b
i=i+1
return b
def PrintFN(m,n):
fiblist=[]
a=1;b=1
while a<=n:
if a>=m:
fiblist.append(a)
a,b=b,a+b
return fiblist
import math
def funcos(eps,x):
i=0;s=0;flag=1
while True:
item=x**i/math.factorial(i)
if abs(item)>=eps:
s=s+flag*item
flag=-flag
i=i+2
else:
break
return s
def acronym(phrase):
words=phrase.split()
res=""
for word in words:
res=res+word[0].upper()
return res
import re, collections, sys
words = "".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]))