西南科大派森期末汇总(简洁版)

        以下代码仅供参考,自己要理解每条语句的含义。

        注意:期末考试不会使用派森系统,而是自己手动上传.py文件。 也不会给你测试反馈,自己可在pycharm上编写完成后测试,若自己认为正确再上传.py文件。 期末监考严格,不要有侥幸心理,平时多花点时间练习。

1、班长选举

voter = {}
for vote in range(8):
    ch = input()
    voter[ch] = voter.get(ch, 0) + 1
sort_voter = sorted(list(voter.items()), key=lambda x: x[1], reverse=True)
print(sort_voter[0][0], sort_voter[0][1])

2、csv转存json格式

import csv
import json

# 读取文件
with open('movie.in', 'r', encoding='utf-8') as f:
    data = f.read()
# 把movie.in文件转换为movie.csv文件
with open('movie.csv', 'w', encoding='utf-8') as f:
    f.write(data)
# 读取csv文件
with open('movie.csv', 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    # 第一行是key。后面的每一行是各自的value
    keys = next(reader)
    rows = [dict(zip(keys, row)) for row in reader]
# 将list转换为json格式
with open('movie.json', 'w', encoding='utf-8') as f:
    json.dump(rows, f, ensure_ascii=False, indent=4)
# json文件存到moive.out文件中
with open('movie.json', 'r', encoding='utf-8') as f:
    data = f.read()
with open('movie.out', 'w', encoding='utf-8') as f:
    f.write(data)

3、csv文件计算

fr = open('salary.in', 'r', encoding='utf-8')
fw = open('salary.out', 'w', encoding='utf-8')
lst = []
for line in fr:
    line = line.replace('\n', '')
    lst.append(line.split(','))
fr.close()
lst[0].append("一季度总收入")
for i in range(1, len(lst)):
    total_income = 0
    for j in range(1, len(lst[i])):
        total_income += int(lst[i][j])
    lst[i].append(str(total_income))
lst[1:] = sorted(lst[1:], key=lambda x: int(x[-1]), reverse=True)
for item in lst:
    fw.write(','.join(item) + '\n')
fw.close()

4、json格式转存csv文件

import json
import csv
with open('movie_inf.in', 'r', encoding='utf-8') as fr:
    data = json.load(fr)
with open('movie_inf.out', 'w', encoding='utf-8') as fw:
    csv_w = csv.writer(fw, lineterminator='\n')
    csv_w.writerow(['片名', '上映年份', '评分', '评价人数', '导演', '编剧', '主演', '类型', '国家/地区', '语言', '时长(分钟)'])
    for item in data:
        csv_w.writerow([item['片名'], item['上映年份'], item['评分'], item['评价人数'], item['导演'], item['编剧'], item['主演'], item['类型'],
                      item['国家/地区'], item['语言'], item['时长(分钟)']])

5、翻转字典的键值对输出

d = {}
A = str(input())
try:
    A_dict = eval(A)
    d = dict(zip(A_dict.values(), A_dict.keys()))
    print(d)
except:
    print("输入错误")

6、歌唱比赛统计

fr = open('sing.in', 'r', encoding='utf-8')
fw = open('sing.out', 'w', encoding='utf-8')
scores = {}
for line in fr:
    items = line.strip().split(',')
    name = items[0]
    score = [float(x) for x in items[1:]]
    score.sort()
    score = score[1:-1]
    average = round(sum(score) / len(score), 2)
    average = '{:.2f}'.format(average)
    scores[name] = average
sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
for name, score in sorted_scores:
    fw.write(f'{name}:{score}\n')

7、公式计算

import math
def f(x):
    sum = 0
    for i in range(0, x+1):
        sum = sum + math.factorial(i)
    print(sum)
n = input()
f(int(n))

#method 2
# n = int(input())
# sum = 1
# product = 1
# for i in range(1,n+1):
#     product = product * i
#     sum = sum + product
# print(sum)

8、集合操作

import random
txt = '''Ifthereisonlyoneargument,itmustbeadictionarymappingUnicode |ordinals(integers)orcharacterstoUnicodeordinals,stringsorNone. |Characterkeyswillbethenconvertedtoordinals. |Iftherearetwoarguments,theymustbestringsofequallength,and |intheresultingdictionary,eachcharacterinxwillbemappedtothe |characteratthesamepositioniny.Ifthereisathirdargument,it |mustbeastring,whosecharacterswillbemappedtoNoneintheresult.'''
new_txt = list(txt)
x, m1, n1, m2, n2 = map(int, input().split())
random.seed(x)
random.shuffle(new_txt)
lt1 = set(new_txt[m1:n1])
lt2 = set(new_txt[m2:n2])
counter1 = 0
for ch in lt1:
    counter1 += 1
print(f'lt1中出现了{counter1}个不同的字符')
counter2 = 0
for ch in lt2:
    counter2 += 1
print(f'lt2中出现了{counter2}个不同的字符')
print('同时出现在lt1和lt2中的字符为:{}'.format(" ".join(sorted(lt1 & lt2))))
print('出现在lt1,但没在lt2中的字符为:{}'.format(" ".join(sorted(lt1 - lt2))))

9、计算日期

pn = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
rn = (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
date = str(input())
year, month, day = map(int, date.split('-'))
days = 0
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
    for i in range(0, month - 1):
        days = days + rn[i]
    total_day = days + day
    print(total_day)
else:
    for i in range(0, month - 1):
        days = days + pn[i]
    total_day = days + day
    print(total_day)

10、简单公式计算

def f(n):
    sum = 0
    if n % 2 !=0:
        for i in range(1, n+1, 2):
            sum = sum + 1/i
    else:
        for i in range(2, n+1, 2):
            sum = sum + 1/i
    #print(round(sum, 2))
    print('%.2f' % sum)

try:
    n = input()
    if len(n) != len(str(int(n))) or int(n) >1000000 or int(n) <= 0:
        print("输入不合法!")
    else:
        f(int(n))
except:
    print("输入不合法!")

11、简单数字加密

def encryption(n):
    string = ''   #定义一个字符串
    for i in n:
        string += str((ord(i)+5) % 10)
    print(string[::-1])
try:
    num = input()
    if len(str(int(num))) != 4:
        print("输入不合法!")
    else:
        encryption(num)
except:
    print("输入不合法!")

12、凯撒密码

text = str(input())
for ch in text :
    if 97 <= ord(ch) <=122:
        ch = chr((ord(ch) + 3 - 97)% 26 + 97)
        print(ch, end='')
    elif 65 <= ord(ch) <= 90:
        ch = chr((ord(ch) + 3 - 65) % 26 + 65)
        print(ch, end='')
    elif 48 <= ord(ch) <= 57:
        ch = chr((ord(ch) + 3 - 48) % 10 + 48)
        print(ch, end='')
    else :
        print(ch, end='')

13、摩斯密码

morse = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
digit = ['-----', '.----', '..---', '...--', '....-', '.....', '-....', '--...', '---..', '----.']
punctuation = {'.': '.-.-.-', ':': '---...', ',': '--..--', ';': '-.-.-.', '?': '..- -..', '=': '-...-', "'": '.----.', '/': '-..-.', '!': '-.-.--', '-': '-....-', '_': '..--.-', '"': '.-..-.', '(': '-.--.', ')': '-.--.-', '$': '...-..-', '&': '·-···', '@': '.--.-.', ' ': ''}
text = str.upper(input())
for ch in text:
    if ord('A') <= ord(ch) <= ord('Z'):
        print(morse[ord(ch) - ord('A')], end=' ')
    elif ord('0') <= ord(ch) <= ord('9'):
        print(digit[ord(ch) - ord('0')], end=' ')
    elif ch in punctuation.keys():
        print(punctuation[ch], end=' ')
    else:
        print(ch, end=' ')

14、摩斯密码解密

morse = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
digit = ['-----', '.----', '..---', '...--', '....-', '.....', '-....', '--...', '---..', '----.']
punctuation = {'.': '.-.-.-', ':': '---...', ',': '--..--', ';': '-.-.-.', '?': '..- -..', '=': '-...-', "'": '.----.', '/': '-..-.', '!': '-.-.--', '-': '-....-', '_': '..--.-', '"': '.-..-.', '(': '-.--.', ')': '-.--.-', '$': '...-..-', '&': '·-···', '@': '.--.-.', ' ': ''}
re_punctuation = dict(zip(punctuation.values(), punctuation.keys()))  #键值对翻转
txt = input().split(' ')
for ch in txt:
    if ch in morse:
        new_ch = chr(morse.index(ch) + ord('a'))
        print(new_ch, end='')
    elif ch in digit:
        new_ch = chr(digit.index(ch) + ord('0'))
        print(new_ch, end='')
    elif ch in re_punctuation.keys():
        new_ch = re_punctuation[ch]
        print(new_ch, end='')
    else:
        print(ch, end='')

#与加密相比,会用到index函数取下标,都借用了ASCII进行转换字符
#该解密还有缺点:解密后的字母都是小写,问题不大

15、扑克牌游戏(考的概率较小)

import random
n = eval(input())
s = eval(input())
rank = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'K': 13, "Q": 12, "J": 11, "A": 14, "okers": 53, "OKERS": 54}
account = [[] for _ in range(n)]
color_level = {"♠":1, "♥":2, "♣":3, "♦":4,"j":5,"J":6}
color = ["♠", "♥", "♣", "♦"]
num = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
poker = [i+j for i in color for j in num]+["jokers", "JOKERS"]
print(f"参与游戏的人数:{n}")
print("新牌顺序")
print(" ".join(poker))
print("洗牌顺序")
random.seed(s)
random.shuffle(poker)
print(" ".join(poker))
print("每个人手上分到的牌")
for i in range(0, 54):
    j = (i) % n
    account[j].append(poker[i])
for i in account:
    print(" ".join(i))
print("每个人手上排序的牌")
for i in account:
    i.sort(key=lambda x: (color_level[x[0]], rank[x[1:]]))
    print(" ".join(i))

16、三角形形状判断

a = int(input())
b = int(input())
c = int(input())
if (a+b > c) and (b+c > a) and (a+c >b) :
    if a == b == c :
        print('等边三角形')
    elif (a == b != c) or (a == c != b) or (b == c != a):
        print('等腰三角形')
    else:
        print('普通三角形')
else:
    print('不构成三角形')

17、食材搭配

menu = input()
for ch in ['#', '$', '%', '&', '*']:
    menu = menu.replace(ch, " ")
lt = menu.split(" ")
lt.sort()
set_lt = sorted(set(lt))
lt2 = []
for i in set_lt:
    for j in set_lt:
        if i != j:
            if str(i + '+' + j) in lt2 or str(i + '+' + j) in lt2:
                pass
            else:
                lt2.append(str(i + '+' + j))
print(*lt2)

18、水仙花数

import math
x = int(input())
a = x % 10  #个位
b = (x % 100 - x % 10)/10  #十位
c = (x - x % 100)/100  #百位
total = math.pow(a, 3) + math.pow(b, 3) + math.pow(c, 3)
if total == x:
    print('是')
else:
    print('不是')

19、素数筛选

def is_prime(x):
    if x < 2:
        return False
    else:
        for i in range(2, int(x ** 0.5)+1):
            if x % i == 0:
                return False
        return True
lt = [eval(i) for i in input().split(' ')]
for i in lt:
    if is_prime(i):
        print(i, end=" ")

20、天气数据筛选

import csv
with open('weather.in', encoding='utf-8', newline='') as fr:
    reader = csv.reader(fr)
    with open('weather.out', 'w', encoding='utf-8', newline='') as fw:
        fw.write("日期,天气状况,最高温,最低温,风力风向\n")
        writer = csv.writer(fw)
        for row in reader:
            if row[1] == '阴' and int(row[3].replace('℃', '').strip()) >= 1:
                writer.writerow(row)

21、维吉尼亚密码

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

22、无穷级数法计算圆周率

threshold = float(input())
flag = 1
i = 1
total = 0
while 1/i >= threshold:
    total = total + 4 * flag * 1/i
    i = i + 2
    flag = -flag
print("%.8f" % total)
#保留小数方法:
#1、使用字符串格式化print("%.mf" % 待处理量) m位
#2、使用python内置函数round(待处理量, 保留小数位)

23、信息存csv文件

fr = open('inf.in', 'r', encoding='utf-8')
fw = open('inf.out', 'w', encoding='utf-8')
fw.write("姓名,手机号,身份证号,居住地\n")
info = {}
count = 0
for line in fr:
    key, value = line.split(":")
    key = key.strip()
    value = value.strip()
    info[key] = value
    count += 1
    if count == 4:
        fw.write(f"{info['姓名']},{info['手机号']},{info['身份证号']},{info['居住地']}\n")
        count = 0
        info = {}
fr.close()
fw.close()

24、信息脱敏

import re
with open(r'data.in.txt', 'r', encoding='UTF-8') as f:   #注意路径
    data = f.read()
data = re.sub(r'姓名:(.{2})(.{1})(.*)', r'姓名:\3\2\1', data)
data = re.sub(r'姓名:(.{1})(.{1})(.*)', r'姓名:\1**', data)
data = re.sub(r'身份证号:(.{6})(.{8})(.*)', r'身份证号:\1********\3', data)
data = re.sub(r'手机号:(.{3})(.{4})(.*)', r'手机号:\1****\3', data)
with open('data.out', 'w', encoding='utf-8') as f:
    f.write(data)
print(data)

25、序列求和

m = int(input())
n = int(input())
total = 0
for x in range(m, n+1):
    if (x % 5 ==0) and (x % 7 ==0) :
        total = total + x
print(total)

26、寻找反素数

def reverse(x):
    x = int(str(x)[::-1])
    return x
def check_huiwen(x):
    if str(x) == str(x)[::-1]:
        return True
    else:
        return False
def is_prime(x):
    if x < 2:
        return False
    for i in range(2, int(x ** 0.5)+1):
        if x % i == 0:
            return False
    return True
m, n = map(int, input().split(" "))
for isprime in range(m, n+1):
    if not check_huiwen(isprime) and is_prime(isprime) and is_prime(reverse(isprime)):
        print(isprime, end=" ")

27、字符统计

import random
txt = '''Ifthereisonlyoneargument,itmustbeadictionarymappingUnicode |ordinals(integers)orcharacterstoUnicodeordinals,stringsorNone. |Characterkeyswillbethenconvertedtoordinals. |Iftherearetwoarguments,theymustbestringsofequallength,and |intheresultingdictionary,eachcharacterinxwillbemappedtothe |characteratthesamepositioniny.Ifthereisathirdargument,it |mustbeastring,whosecharacterswillbemappedtoNoneintheresult.'''
txt_lt = list(txt)
x, m, n = map(int, input().split(" "))
random.seed(x)
random.shuffle(txt_lt)
txt_lt = txt_lt[m: n+1]
counter = {}
for ch in txt_lt:
    counter[ch] = counter.get(ch, 0) + 1
txt_lt = sorted(list(counter.items()), key=lambda x:x[1],reverse=True)
for key, value in txt_lt[0:5]:
    print(f'{key}:{value}')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值