Python语言基础编程速通54题
使用OpenJudge上面的题集。
实用Python程序设计测验汇总(2022秋季)。
1 字符菱形
ch = input()
for i in range(1,6):
if i <= 3:
print(" "*(3-i)+ch*(2*i-1))
else:
print(" "*(i-3)+ch*(5-(i-3)*2))
2 字符三角形
# 2 字符三角形
ch = input()
print(" "*2+ch)
print(" "+ch*3)
print(ch*5)
3 输出第二个整数
# 3 输出第二个整数
ls = input().split()
print(ls[1])
4 求三个数的和
# 4 求三个数的和
text = input().split()
sum = 0
for i in text:
sum += float(i)
print(sum)
5 判断子串
# 5 判断子串
son = input()
father = input()
if son in father:
print("YES")
else:
print("NO")
6 计算(a+b)*c的值
# 6 计算(a+b)*c的值
a,b,c=map(int,input().split())
sum=(a+b)*c
print(sum)
7 反向输出一个三位数
切片操作语法:
str[start:stop:step] # 其中依次表示为[开始索引:结束索引:步长]
其中是左闭右开区间,步长 step 可以为负数
# 7 反向输出一个三位数
a = input()
print(a[::-1])
8 字符串交换
切片。
# 8 字符串交换
str1 = input()
str2 = input()
s1 = str1[0:2] + str2[2:4]
s2 = str2[0:2] + str1[2:4]
print(s2+'\n'+s1)
9 字符串中的整数求和
# 9 字符串中的整数求和
a,b = map(str,input().split())
c = int(a[0:2])+int(b[0:2])
print(c)
10 计算2的幂
# 10 计算2的幂
mi = int(input())
mul = 1
for i in range(mi):
mul *= 2
print(mul)
11 计算多项式的值
格式化字符串,也可以使用format。
# 11 计算多项式的值
x, a, b, c, d = map(float, input().split())
y = a*x**3 + b*x**2 + c*x + d
print("%.7f"%y)
12 奇偶性判断
# 12 奇偶数判断
n = int(input())
if n%2:
print("odd")
else:
print("even")
13 点和正方形的关系
判断条件。
# 13 点和正方形的关系
x, y = map(int, input().split())
if x <= 1 and x >= -1:
if y <=1 and y >= -1:
print("yes")
else:
print("no")
else:
print("no")
14 三角形判断
# 14 三角形判断
a, b, c = map(int, input().split())
if a+b>c and b+c>a and a+c>b:
print("yes")
else:
print("no")
15 计算邮资
# 15 计算邮资
menu = input().split()
a = int(menu[0])
sum = 0
if a > 1000:
b = int((a-1000)/500)
if (a-1000)%500>0:
sum = 8 + (b + 1) * 4
else:
sum = 8 + b * 4
else:
sum += 8
if menu[1] == 'y':
print(sum+5)
else:
print(sum)
16 分段函数
# 16 分段函数
x = float(input())
y = 0
if x >= 0 and x < 5:
y = -x + 2.5
elif x >= 5 and x < 10:
y = 2 - 1.5*(x-3)*(x-3)
elif x >= 10 and x < 20:
y = x / 2 - 1.5
print("%.3f"%y)
17 简单计算器
# 17 简单计算器
s = input().split()
str = s[0] + s[2] + s[1]
symbol = ['+', '-', '*', '/']
if s[2] in symbol:
if s[2]=='/' and s[1] == '0':
print("Divided by zero!")
else:
print(int(eval(str)))
else:
print("Invalid operator!")
18 大象喝水
最初,是在lua语言中,math.ceil(x)返回大于等于参数x的最小整数,即对浮点数向上取整.
# 18 大象喝水
import math
h, r = map(int, input().split())
PI = 3.14159
v = h*PI*r*r
num = 20000/v
print(math.ceil(num))
19 苹果和虫子2
# 19 苹果和虫子2
import math
n, x, y = map(int, input().split())
res = n - math.ceil(y/x)
if res < 0:
res = 0
print(res)
20 求整数的和与均值
# 20 求整数的和与均值
n = int(input())
sum = 0
for i in range(n):
sum += int(input())
print("%d"%sum+" "+"%.5f"%(sum/n))
21 整数序列的元素最大跨度值
# 21 整数序列的元素最大跨度值
n = int(input())
array = input().split()
array = [int(i) for i in array]
print(max(array)-min(array))
22 奥运奖牌计数
# 22 奥运奖牌计数
n = int(input())
jin = 0
yin = 0
tong = 0
for i in range(n):
array = input().split()
array = [int(i) for i in array]
jin += array[0]
yin += array[1]
tong += array[2]
print("%d"%jin+" "+"%d"%yin+" "+"%d"%tong+" "+"%d"%(jin+yin+tong))
23 鸡尾酒疗法
# 23 鸡尾酒疗法
n = int(input())
x0 = input().split()
baseline = float(x0[1])/float(x0[0])
for i in range(n-1):
x1 = input().split()
a = float(x1[1])/float(x1[0])
sub = a -baseline
if sub > 0.05:
print("better")
elif sub < -0.05:
print("worse")
else:
print("same")
24 角谷猜想
# 24 角谷猜想
n = int(input())
while n!=1:
if n % 2:
print(str(n)+"*3+1="+str(n*3+1))
n=n*3+1
else:
print(str(n)+"/2=%d"%(n/2))
n//=2
print("End")
25 正常血压
# 25 正常血压
n = int(input())
total = 0
maxtotal = 0
for i in range(n):
s = input().split()
a, b = int(s[0]), int(s[1])
if 90<=a<=140 and 60<=b<=90:
total+=1
if maxtotal<total:
maxtotal = total
else:
total = 0
print(maxtotal)
26 数字反转
# 26 数字反转
n = int(input())
while n%10 == 0:
n = int(n/10)
n = str(n)
if n[0] == '-':
print("-"+n[:0:-1])
else:
print(n[::-1])
27 求特殊自然数
# 27 求特殊自然数
def stoi(n, i):
if i < 2 or i > 10:
return -1
ys = ""
while n >= i:
ys = str(n%i) + ys
n //= i
ys = str(n) + ys
return ys
for i in range(1,999):
if len(stoi(i, 7)) == 3 and len(stoi(i, 9)) == 3:
if str(stoi(i, 7)) == str(stoi(i, 9))[::-1]:
print(i)
print(stoi(i, 7))
print(stoi(i, 9))
28 数字统计
# 28 数字统计
l, r = map(int, input().split())
c = ""
for i in range(l, r + 1):
c += str(i)
sum = 0
for j in c:
if j == '2':
sum += 1
print(sum)
29 求最大公约数问题
# 29 求最大公约数问题
a, b = map(int, input().split())
if a < b:
a, b = b, a
while a % b:
a, b = b, a%b
print(b)
30 多少种取法
# 30 多少种取法
def ways(m, n, s):
if m > s:
return ways(s, n, s)
elif n == 0 and s == 0:
return 1
elif m == 0 or s == 0:
return 0
else:
return ways(m-1,n-1,s-m)+ways(m-1,n,s)
n = int(input())
for i in range(n):
m, n, s = map(int, input().split())
print(ways(m, n, s))
31 石头剪刀布
# 31 石头剪刀布
n, a, b = map(int, input().split())
aScore, bScore = 0, 0
na = [int(i) for i in input().split()]
nb = [int(i) for i in input().split()]
for k in range(n):
if (na[k%a]==2 and nb[k%b]==5) or (na[k%a]==5 and nb[k%b]==0) or (na[k%a]==0 and nb[k%b]==2):
aScore += 1
elif na[k%a] == nb[k%b]:
pass
elif (na[k%a]==5 and nb[k%b]==2) or (na[k%a]==0 and nb[k%b]==5) or (na[k%a]==2 and nb[k%b]==0):
bScore += 1
if aScore > bScore:
print('A')
elif aScore == bScore:
print('draw')
elif aScore < bScore:
print('B')
32 统计数字字符个数
# 32 统计数字字符个数
s = input()
ret = 0
for i in range(len(s)):
if s[i].isdigit():
ret += 1
print(ret)
33 大小写字母互换
# 33 大小写字母互换
s = input()
for c in s:
if 'a' <= c <= 'z':
print(chr(ord(c) - 32 ),end="")
elif 'A' <= c <= 'Z':
print(chr(ord(c) + 32),end="")
else:
print(c,end="")
34 过滤多余的空格
# 34 过滤多余的空格
s = input()
for i in range(len(s)):
if s[i] == ' ' and s[i-1] == ' ':
print('', end='')
else:
print(s[i], end='')
35 找第一个只出现一次的字符
# 35 找第一个只出现一次的字符
s = input()
flag = 1
for i in range(len(s)):
if s.count(s[i]) == 1:
print(s[i])
flag = 0
break
if flag:
print('no')
36 判断字符串是否为回文
# 36 判断字符串是否为回文
s = input()
flag = 1
length = int(len(s)/2)
for i in range(length):
if s[i] != s[len(s)-1-i]:
print("no")
flag = 0
break
if flag:
print("yes")
37 字符串最大跨距
# 37 字符串最大跨距
SS = input().split(",")
s,s1,s2 = SS[0],SS[1],SS[2]
a = s.find(s1)
b = s.rfind(s2)
c = len(s1)
if b-a-c >= 0:
print(b-a-c)
else:
print("-1")
38 找出全部子串位置
# 38 找出全部子串位置
n = int(input())
for i in range(n):
s = input().split()
m = 0
if s[1] not in s[0]:
print('no',end='')
for j in s[0]:
a = s[0].find(s[1], m)
if a == -1:
continue
else:
m = a + len(s[1])
print(a, end=' ')
print("")
39 万年历
# 39 万年历
n = int(input())
def days_of_week(year, mon, day):
list1 = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] #闰年2月份为29天
list2 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] #平年2月份为28天
date = 0
years = 0
lst_days = [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday"
]
if (year % 4 == 0) & (year % 100 != 0) or year % 400 == 0:
if mon in [1, 3, 5, 7, 8, 10, 12]:
if day < 1 or day > 31:
print('Illegal')
return
elif mon == 2:
if day < 1 or day > 29:
print('Illegal')
return
elif mon in [4, 6, 9, 11]:
if day < 1 or day > 30:
print('Illegal')
return
else:
print('Illegal')
return
else:
if mon in [1, 3, 5, 7, 8, 10, 12]:
if day < 1 or day > 31:
print('Illegal')
return
elif mon == 2:
if day < 1 or day > 28:
print('Illegal')
return
elif mon in [4, 6, 9, 11]:
if day < 1 or day > 30:
print('Illegal')
return
else:
print('Illegal')
return
#输入的年份大于等于2018年的判断过程如下:
if year >= 2018:
for j in range(2018, year):
if (j % 4 == 0) & (j % 100 != 0) or j % 400 == 0: #闰年
years += 366
else: #平年
years += 365 #闰年天数加366天,平年加365天
if ((year % 4) == 0) & ((year % 100) != 0) or ((year % 400) == 0):
for i in range(mon - 1):
date += list1[i] #闰年月份按list1相加
days = date + day
else:
for i in range(mon - 1):
date += list2[i] #平年月份按list2相加
days = date + day
total = days + years
ji = total % 7 #参考日期是2018年1月1号是星期一
#由于"ji=0"时,输出的结果是"星期0",因此对"ji"进行了判断,使"ji=0"时输出的结果为"星期7"
print(lst_days[ji])
#输入的年份小于2018年的判断过程如下:
else:
for j in range(year + 1, 2018):
if (j % 4 == 0) & (j % 100 != 0) or j % 400 == 0:
years += 366
else:
years += 365
if ((year % 4) == 0) & ((year % 100) != 0) or ((year % 400) == 0):
for i in range(mon - 1, 12):
date += list1[i]
days = date - day + 1
else:
for i in range(mon - 1, 12):
date += list2[i]
days = date - day + 1
total = days + years
ji = total % 7
print(lst_days[(8 - ji)%7])
for i in range(n):
year, mon, day = map(int, input().split())
days_of_week(year, mon, day)
40 成绩排序
# 40 成绩排序
a = []
swp = {}
num = int(input())
for i in range(num):
b = input().split()
b[1] = int(b[1])
a.append({"name":b[0], 'score':b[1]})
for i in range(num):
for j in range(i+1, num):
if a[i]["score"] < a[j]["score"] or (a[i]["score"] == a[j]["score"] and a[i]["name"] > a[j]["name"]):
swp = a[i]
a[i] = a[j]
a[j] = swp #冒泡排序
for i in range(num):
print("%s %d"%(a[i]["name"],a[i]["score"]))
41 图像模糊处理
# 41 图像模糊处理
import copy
n,m = map(int,input().split())
a = []
for i in range(n):
lst = list(map(int,input().split()))
a.append(lst)
b = copy.deepcopy(a) # b = a[:] 是浅拷贝,不行
for i in range(1,n-1):
for j in range(1,m-1):
b[i][j] = round((a[i][j] + a[i-1][j] + a[i+1][j] + a[i][j-1] + a[i][j+1])/5)
for i in range(0,n):
for j in range(0,m):
print(b[i][j],end = " ")
print("")
42 向量点积计算
# 42 向量点积计算
n = int(input())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
vetSum = 0
for i in range(n):
vetSum += a[i]*b[i]
print(vetSum)
43 病人排队
# 43 病人排队
n = int(input())
a = []
for i in range(n):
s = input().split()
lst = [str(s[0]),int(s[1])] #添加上登记顺序
a.append(lst)
def KEY(x):
if x[1]>=60:
return-x[1] #年龄从大到小
else:
return 0
a.sort(key=KEY) #key为自定义比较函数,按函数f的方式比较
for i in range(n):
print(a[i][0])
44 矩阵乘法
# 44 矩阵乘法
m, n, k = map(int, input().split())
A = []
B = []
for i in range(m):
A.append(list(map(int, input().split())))
for i in range(n):
B.append(list(map(int, input().split())))
C = [[0 for i in range(k)] for i in range(m)]
for i in range(m):
for j in range(k):
for q in range(n):
C[i][j] += A[i][q] * B[q][j]
print(C[i][j], end=' ')
print("")
45 回文子串
# 45 回文子串
s = input()
n = len(s)
res = []
for i in range(0, n-1):
for j in range(i+1, n):
if s[i: j+1] == s[j:i:-1] + s[i]:
tmpList = [j-i+1, i, s[i:j+1]]
res.append(tmpList)
res.sort()
for i in range(len(res)):
print(res[i][2])
46 校园食宿预订系统
# 46 校园食宿预订系统
n, m = map(int,input().split())
t={}
for i in range(m):
s = input().split()
name, price, num =s[0], int(s[1]), int(s[2])
t[name]=[price,num]
total = 0
for i in range(n):
names = input().split()
for name in names:
if t[name][1]>0:
total += t[name][0]
t[name][1] -= 1
print(total)
47 找出所有整数
# 47 找出所有整数
import re
m = '[0-9]+'
while True:
try:
s = input()
lst = re.findall(m,s)
for x in lst:
print(x)
except:
break
48 找出所有整数和小数
# 48 找出所有整数和小数
import re
m='[0-9]+\.[0-9]+|[0-9]+'
while True:
try:
s = input()
lst = re.findall(m,s)
for x in lst:
print(x)
except:
break
49 找出小于100的整数
# 49 找出小于100的整数
import re
m = r"(^|[^0-9-])(\d{1,2})([^0-9]|$)"
for i in range(2):
s = input()
lst = re.findall(m,s)
for x in lst:
# // 在此处补充你的代码
print(x[1])
50 密码判断
# 50 密码判断
import re
m='[A-Za-z][-A-Za-z0-9_]{7,}\Z'
while True:
try:
s = input()
if re.match(m,s) != None:
print("yes")
else:
print("no")
except:
break
51 寻找h3
# 51 寻找h3
import re
m = \
'<h3>(.*?)</h3>'
for x in re.findall(m,"cdef<h3>abd</h3><h3>bcK</h3><h3>123</h3>KJM"):
print(x)
52 找<>中的数
# 52 找<>中的数
n=int(input())
import re
for i in range(n):
s=input()
m='<(0|[1-9][0-9]{0,2})>'
result=re.findall(m,s)
if result==None:
print("NONE")
elif len(result)==0:
print("NONE")
else:
for x in result:
print(x,end=" ")
print("")
53 手机号码
# 53 手机号码
import re
n=int(input())
isfirstprint=True
for j in range(n):
s = input()
m = '<(.+?)>(.*?)</\\1>'
result = re.findall(m, s)
if len(result) == 0:
if not isfirstprint:
print("\n",end="")
print("NONE",end="")
isfirstprint=False
else:
isNone = True
for x in result:
# 查找电话号码
m = '\([0-9]{1,2}\)-[0-9]{3,}'
phone_maybe = re.findall(m, x[1])
if len(phone_maybe) == 0:
continue
else:
phone = []
for tmp in phone_maybe:
if len(re.findall('-[0-9]+', tmp)[0]) < 5:
phone += re.findall('\(([0-9]{1,2})\)-[0-9]{3,}', tmp)
if len(phone) > 0:
isNone=False
if not isfirstprint:
print("")
isfirstprint=False
print("<" + x[0] + ">", end="")
isFirstPrinthere=True
for tt in phone:
if not isFirstPrinthere:
print(",", end="")
print(tt, end="")
isFirstPrinthere=False
print("</" + x[0] + ">",end="")
if isNone==True:
if not isfirstprint:
print("")
print("NONE",end="")
isfirstprint=False
54 时间处理
# 54 时间处理
import datetime
s=[]
t=[]
while True:
try:
s.append(input())
except:
break
for i in range(len(s)):
if i%2==0:
if len(s[i].split())==5:
a=datetime.datetime.strptime(s[i],'%Y %m %d %H %M')
else:
a = datetime.datetime.strptime(s[i], '%m-%d-%Y %H:%M %p')
else:
ss=s[i].split()
if len(ss)==1:
a+=datetime.timedelta(seconds=int(ss[0]))
else:
a+=datetime.timedelta(days=int(ss[0]),hours=int(ss[1]),minutes=int(ss[2]))
t.append(a)
for i in t:
print(i)