翻转字典的键值对输出 a = input() try: b = eval(a) c = {} for d in b: c[b[d]] = d print(c) except: print("输入错误") 班长选举 dic = { "Tom": 0, "Rose": 0, "Bill": 0, } i=0 while i < 8: vote = str(input()) if vote == 'Tom': dic["Tom"] = dic["Tom"] + 1 elif vote == 'Rose': dic["Rose"] = dic["Rose"] + 1 elif vote == 'Bill': dic["Bill"] = dic["Bill"] + 1 else: continue i += 1 max = 0 name = '' for key, value in dic.items(): if value > max: max = value name = key print(name, max) def py(error): a = 1 b = 1 sum = 0 while 1 / b > error: if a % 2 != 0: sum += 1 / b else: sum -= 1 / b a += 1 b += 2 pi = sum * 4 return pi if __name__ == '__main__': threshold = float(input()) print("{:.8f}".format(py(threshold))) 简单数字加密 try: s = input() if len(str(int(s))) != 4: print("输入不合法!") else: txt = "" for i in s: txt += str((ord(i) + 5) % 10) print(txt[::-1]) except Exception: print("输入不合法!") 食材搭配 str1 = input() each_food = "" food = {} for ch in str1: if ord(ch) < 2000: food[each_food] = 0 each_food = "" else: each_food += ch food[each_food] = 0 food = list(food.keys()) food.sort(key=lambda x: int(ord(x[0]))) food_match = [] for i in range(len(food)): for j in range(i + 1, len(food)): food_match.append(food[i] + "+" + food[j]) food_match.sort(key=lambda x: int(ord(x[0]))) for ch in food_match: print(ch, end=' ') | txt = input() lt = txt.split() lt_num = {} for ch in lt: lt_num[ch] = lt_num.get(ch, 0) + 1 sort_lt = sorted(lt_num.items(), key=lambda x: x[1], reverse=True) print("出现频率最高的三个单词是:") for ch in sort_lt[:3]: print("{:^5}:{:^3}次".format(ch[0].lower(), ch[1])) 凯撒加密 s = input() t = "" for c in s: if 'a' <= c <= 'z': t += chr( ord('a') + ((ord(c)-ord('a')) + 3 )%26 ) elif 'A' <= c <= 'Z': t += chr( ord('A') + ((ord(c)-ord('A')) + 3 )%26 ) elif '0' <= c <='9': t+= chr( ord('0') + ((ord(c)-ord('0')) + 3 )%26 ) else: t +=c print(t) 扑克牌游戏 import random def card_weight(lst): values = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14, "okers": 15, "OKERS": 16} suits = {'♦': 4, '♣': 3, '♥': 2, '♠': 1, "j": 5, "J": 6} value, suit = lst[1:], lst[0] return values[value] + suits[suit] * 100 x = int(input()) y = int(input()) print("参与游戏的人数:{}".format(x)) print("新牌顺序") s = "♠2 ♠3 ♠4 ♠5 ♠6 ♠7 ♠8 ♠9 ♠10 ♠J ♠Q ♠K ♠A ♥2 ♥3 ♥4 ♥5 ♥6 ♥7 ♥8 ♥9 ♥10 ♥J ♥Q ♥K ♥A ♣2 ♣3 ♣4 ♣5 ♣6 ♣7 ♣8 ♣9 ♣10 ♣J ♣Q ♣K ♣A ♦2 ♦3 ♦4 ♦5 ♦6 ♦7 ♦8 ♦9 ♦10 ♦J ♦Q ♦K ♦A jokers JOKERS" print(s) q = s.split() random.seed(y) random.shuffle(q) print("洗牌顺序") print(" ".join(q)) print("每个人手上分到的牌") for i in range(1, x + 1): lst = q[i - 1::x] print(' '.join(lst)) print("每个人手上排序的牌") for i in range(1, x + 1): lst = q[i - 1::x] lst = sorted(lst, key=card_weight) print(' '.join(lst)) 日期计算 import datetime str=input() arr=str.split('-') d1=datetime.datetime(int(arr[0]),int(arr[1]),int(arr[2])) d2=datetime.datetime(int(arr[0]),1,1) print((d1-d2).days+1) 摩斯密码翻译器 morse = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."] digit = ['-----', '.----', '..---', '...--', '....-', '.....', '-....', '--...', '---..', '----.'] punctuation = { '.': '.-.-.-', ':': '---...', ',': '--..--', ';': '-.-.-.', '?': '..- -..', '=': '-...-', "'": '.----.', '/': '/', '!': '-.-.--', '-': '-....-', '_': '..--.-', '"': '.-..-.', '(': '-.--.', ')': '-.--.-', '$': '...-..-', '&': '·-···', '@': '.--.-.', ' ': '' } s = input() for i in s: if i.isalpha(): print(morse[ord(i.lower()) - ord('a')], end=' ') elif i.isdigit(): print(digit[int(i)], end=' ') elif i in punctuation: print(punctuation[i], end=' ') else: print(i, end=' ') |
字符统计 import random txt= '''Ifthereisonlyoneargument,itmustbeadictionarymappingUnicode |ordinals(integers)orcharacterstoUnicodeordinals,stringsorNone. |Characterkeyswillbethenconvertedtoordinals. |Iftherearetwoarguments,theymustbestringsofequallength,and |intheresultingdictionary,eachcharacterinxwillbemappedtothe |characteratthesamepositioniny.Ifthereisathirdargument,it |mustbeastring,whosecharacterswillbemappedtoNoneintheresult.''' list = [] for i in txt: list.append(i) x, a, b = map(int, input().split()) random.seed(x) random.shuffle(list) List1 = list[a:b+1] Dict1 = {} for i in List1: Dict1[i] = Dict1.get(i, 0) + 1 SortDict = sorted(Dict1.items(), key=lambda x: x[1], reverse=True) for i in range(0, 5): print("{}:{}".format(SortDict[i][0], SortDict[i][1])) 集合操作 import random txt = '''Ifthereisonlyoneargument,itmustbeadictionarymappingUnicode |ordinals(integers)orcharacterstoUnicodeordinals,stringsorNone. |Characterkeyswillbethenconvertedtoordinals. |Iftherearetwoarguments,theymustbestringsofequallength,and |intheresultingdictionary,eachcharacterinxwillbemappedtothe |characteratthesamepositioniny.Ifthereisathirdargument,it |mustbeastring,whosecharacterswillbemappedtoNoneintheresult.''' lt = [] x, m1, n1, m2, n2 = map(int, input().split()) for i in txt: lt.append(i) random.seed(x) random.shuffle(lt) lt1 = lt[m1:n1] lt2 = lt[m2:n2] lt1 = list(set(lt1)) lt2 = list(set(lt2)) print("lt1中出现了%d个不同的字符" % len(lt1)) # 输出lt2中不同的字符个数 print("lt2中出现了%d个不同的字符" % len(lt2)) lt1 = set(lt1) lt2 = set(lt2) lt3 = lt1 & lt2 lt4 = lt1 - lt3 # 给lt3排序输出 lt3 = list(lt3) lt3.sort() print("同时出现在lt1和lt2中的字符为:", end="") for i in lt3: print(i, end=" ") print() # 给lt4排序输出 lt4 = list(lt4) lt4.sort() print("出现在lt1,但没在lt2中的字符为:", end="") for i in lt4: print(i, end=" ") 素数筛选 a,b = list(map(int, input().split())) m = "" for ch in range(a,b+1): for k in range(2,ch): if ch % k ==0: break else: m += str(ch) + ' ' print(m) | ISBN判别 isbn = input().split('-') ko = "" for i in isbn: ko +=i a = ko[:9] m = 10 s = 0 for i in a[:9]: n = int(i) * m s += n m -= 1 s = s % 11 s = 11 - s if int(ko[9:]) == s: print("正确") else: k = ko[:9] + str(s) print("不正确\n正确的应该是{}".format(k)) 公式计算 import math m = int(input()) sum1 = 0 for i in range(m+1): sum1 += math.factorial(i) print(sum1) 寻找反素数 def find(a): for temp in range(2, a // 2 + 1): if a % temp == 0: return False return True m, n = map(int, input().split()) lt1 = [] for i in range(m, n + 1): if i // 10 > 0 and str(i) != str(i)[::-1] and find(i) and find(int(str(i)[::-1])): print(i, end=' ') 信息脱敏 fr = open('data.in', 'r', encoding='utf-8') fw = open('data.out', 'w', encoding='utf-8') for line in fr: if line[0] == "姓": line = line.replace(line[3:5], "*" * len(line[3:5])) line = line[3:6][::-1] fw.write("姓名:" + line + '\n') elif line[0] == "身": line = line.replace(line[11:19], "*" * len(line[11:19])) fw.write(line) elif line[0] == "手": line = line.replace(line[7:11], "*" * len(line[7:11])) fw.write(line) else: fw.write(line) fr.close() fw.close() import json fr=open('movie.in','r', encoding='utf-8') fw=open('movie.out','w',encoding='utf-8’) lst = [] for line in fr: line = line.replace("\n", "") lst.append(line.split(",")) fr.close() for i in range(1, len(lst)): lst[i] = dict(zip(lst[0], lst[i])) json.dump(lst[1:],fw,indent=4, ensure_ascii=False) fw.close() 水仙花判定 a = input() a1 = int(a) b = int(a[0]) c = int(a[1]) d = int(a[2]) if a1 == (pow(b,3) + pow(c,3) + pow(d,3)): print("是") else: print("不是") |
fr = open('weather.in', 'rt', encoding='utf-8')
s = fr.readlines()
lst = []
for i in range(1, len(s)):
s[i]= s[i].split(",")
for i in range(1,len(s)):
if s[i][1] == "阴" and int (s[i][3][:2]) >= 1:
lst.append(s[i])
a = ""
a += s[0]
for i in range(len(lst)):
for j in range(len(lst[i])):
a +=lst[i][j]
if j!=4:
a += ','
fw = open('weather.out', 'w',encoding='utf-8')
fw.writelines(a)
fr.close()
fw.close()
维吉尼亚解密
secret_key = input().lower()
plain_text = input()
a = []
b = []
c = []
for i in range(26):
aa = [chr((i + j) % 26 + 65) for j in range(26)]
a.append(aa)
for i in range(26):
bb = [chr((i + j) % 26 + 97) for j in range(26)]
b.append(bb)
for i in range(10):
cc = [chr((i + j) % 10 + 48) for j in range(10)]
c.append(cc)
n = 0
for ch in plain_text:
if ch.isupper():
print(a[ord(secret_key[n % len(secret_key)]) - 97][ord(ch) - 65], end='')
elif ch.islower():
print(b[ord(secret_key[n % len(secret_key)]) - 97][ord(ch) - 97], end='')
elif ch.isdigit():
print(c[(ord(secret_key[n % len(secret_key)]) - 97) % 10][ord(ch) - 48], end='')
elif ch == " ":
print(ch, end='')
n -= 1
else:
print(ch, end='')
n += 1
兔子问题
def rabbit(month):
if month <= 2:
return 2
else:
return rabbit(month-1)+rabbit(month-2)
if __name__=="__main__":
month=int(input())
print (int(rabbit(month)/2))
峰值查找
# 找到峰值并返回其索引
def find_peak(nums):
n = len(nums)
left, right = 0, n - 1
# 二分查找
while left < right:
mid = (left + right) // 2
if nums[mid] > nums[mid + 1]:
right = mid
else:
left = mid + 1
return left
nums = list(map(int, input().split()))
index = find_peak(nums)
print(index)
import datetime
def is_leap(year):
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
return True
else:
return False
def check_date(y, m, d):
if y < 1900 or y > datetime.date.today().year: #年份应该在1900年到当前所在年份之间
return False
if m < 1 or m > 12: #月份应该在1-12之间
return False
if d < 1:
return False
elif m == 2:
if is_leap(y): #闰年二月最多29天
if d > 29:
return False
else:
if d > 28:
return False
elif m in [4, 6, 9, 11]: #4、6、9、11月30天
if d > 30:
return False
else:
if d > 31: #其它月份31天
return False
return True
def is_digits(ss):
for s in ss:
if not s.isdigit():
return False
return True
weights = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2] #权重
M_codes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'] #除以11的余数对应的校验码
idid = input()
if len(idid) != 18: #不足18位
print('身份证无效')
elif not is_digits(idid[:17]): #号码的前17位不全是数
print('身份证无效')
elif is_digits(idid[:17]):
year = int(idid[6:10])
month = int(idid[10:12])
day = int(idid[12:14])
if check_date(year, month, day) == False: #判断日期是否合法
print('身份证无效')
else:
total = 0
for j in range(17):
total += int(idid[j]) * weights[j] #计算验证码
z = total % 11
if M_codes[z] != idid[17]: #第18位验证码不正确
print('身份证无效')
else:
print('身份证有效')
青蛙跳
def frog(n):
if n == 1:
return 1
if n == 2:
return 2
return frog(n - 1) + frog(n - 2)
num=int(input())
sum = frog(num)
print(sum)
销售数据统计
import csv
with open("sale.in", "r", encoding="utf-8") as f:
reader = csv.reader(f)
a = next(reader)
a.append("年度总销售量")
b = []
for i in reader:
s = 0
for j in range(1, 13):
s += int(i[j])
i.append(s)
b.append(i)
b.sort(key=lambda x: x[13], reverse=True)
fw = open("sale.out", "w", encoding="utf-8")
fww = csv.writer(fw)
fww.writerow(a)
fww.writerows(b)
fw.close()
import csv
import json
# 读取JSON文件
with open('movie_inf.in', 'r',encoding='utf-8') as f:
data = json.load(f)
# 获取JSON数据的键名列表
header = list(data[0].keys())
With open('movie_inf.out', 'w', newline='',encoding='utf-8') as fi:
writer = csv.writer(fi)
writer.writerow(header)
for row in data:
writer.writerow(row.values())
歌唱比赛
with open('sing.in','r',encoding='utf-8') as f:
num=f.readlines()
f.close()
date=[]
def max_num(list):
max=list[0]
for i in list:
if max<i:
max=i
return max
def min_num(list):
min = list[0]
for i in list:
if min > i:
min = i
return min
def re_num(list):
sum=0.0
for i in list:
sum+=i
return "%.2f"%(sum/len(list))
for con in num:
str=[]
str2=[]
str=con.split(sep=',')
str2.append(str[0])
num=[]
for i in range(1,11):
num.append(float(str[i]))
num.remove(max_num(num))
num.remove(min_num(num))
str2.append(re_num(num))
date.append(str2)
for i in range(len(date)):
for j in range(i,len(date)):
if date[i][1]<date[j][1]:
temp=date[i]
date[i]=date[j]
date[j]=temp
for i in date:
print(i[0],i[1],sep=' ',end=' ')
print('')
with open('sing.out','w',encoding='utf-8') as f:
for con in date:
st=':'.join(con)
st=st+'\n'
f.write(st)
f.close()
数组接雨
class Solution:
def trap(self, height):
def max_height(nums, start, end):
max_val = 0
for index in range(start, end + 1):
if nums[index] > max_val:
max_val = nums[index]
return max_val
res = 0
lens = len(height)
for i in range(1, lens - 1):
left_max = max_height(height, 0, i - 1)
right_max = max_height(height, i + 1, lens - 1)
lower_max = min(left_max, right_max)
if lower_max > height[i]:
res += (lower_max - height[i])
return res
solution = Solution()
height1 = input()
height=[int(num) for num in height1.split(',')]
print(solution.trap(height))
import csv
# 读取inf.in文件
with open('inf.in', 'r', encoding='utf-8') as file:
lines = file.readlines()
# 解析个人身份信息
records = []
record = {}
for line in lines:
line = line.strip()
if line.startswith("姓名"):
if record:
records.append(record)
record = {}
record["姓名"] = line.split(":")[1]
elif line.startswith("居住地"):
record["居住地"] = line.split(":")[1]
elif line.startswith("身份证号"):
record["身份证号"] = line.split(":")[1]
elif line.startswith("手机号"):
record["手机号"] = line.split(":")[1]
# 添加最后一个记录
if record:
records.append(record)
# 写入inf.out文件
with open('inf.out', 'w', encoding='utf-8', newline='') as file:
writer = csv.DictWriter(file, fieldnames=["姓名", "手机号", "身份证号", "居住地"])
writer.writeheader()
writer.writerows(records)
传感器数据分析
with open('sensor_data.in', 'r', encoding='utf-8') as input_file, open('sensor_data.out', 'w', encoding='utf-8') as output_file:
for line in input_file:
# 分割每行数据
data = line.strip().split()
# 提取光照值和时间
time = data[1]
illuminance = float(data[4])
# 判断光照是否大于47
if illuminance > 47:
# 将时间和光照写入输出文件
output_file.write(f"{time} {illuminance}\n")
回文数字
x = str(input())
if x == x[::-1]:
print("True")
else:
print("False")
a = list(map(float, input().split()))
a.sort()
s = sum(a) / len(a)
m = len(a) >> 1
if len(a) % 2 == 0:
median = (a[m - 1] + a[m]) / 2
else:
median = a[m]
print(f"最大值:{a[-1]},最小值:{a[0]},平均值:{s:.2f},中位数:{median:.2f}")
def fun(n):
s = 0
if n % 2 != 0:
for i in range(1, n + 1, 2):
s += 1 / i
print(f"{s:.2f}")
else:
for i in range(2, n + 1, 2):
s += 1 / i
print(f"{s:.2f}")
try:
a = input()
if a[0] != '0' and 0 < int(a) <= 1000000:
fun(int(a))
else:
print("输入不合法!")
except:
print("输入不合法!")