(SWUST)《Python程序设计方法与实践》题库

P18 Python期末成绩


小明最近学习了Python课,这门课程的总成绩计算方法是:总成绩=平时作业成绩×20%+阶段测试成绩×30%+期末机考成绩×50% (课程实际评分规则请以任课教师要求为准) 小明想知道,这门课程自己最终能得到多少分。

A, B, C = map(int, input().split())
print(int(A * 0.2 + B * 0.3 + C * 0.5))


P31 翻转字典的键值对输出


读入一个字典类型的字符串,反转其中的键值对输出。 即,读入字典key:value模式,输出value:key模式。

try:
    d = eval(input())
    reverse_dict = dict(zip(d.values(), d.keys()))
    print(reverse_dict)
except:
    print("输入错误")


P32 班长选举


班级进行班长选举,有三个候选人Tom、Rose、Bill。班委会人数8,每人投一票,票面为候选人姓(Tom、Rose、Bill),姓名如果不存在,则选票作废。统计各候选人得票数,并输出得票数最高的姓名和票数。输入格式为每个人名占一行输入。

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


P46 寻找不含重复字符的子串


给定一个字符串 s,找出其中所有不含重复字符的子串,并将它们按照字典序排序后输出。

s = input()
def find(s):
    n = len(s)
    res = []
    for i in range(n):
        for j in range(i + 1, n + 1):
            if len(set(s[i:j])) == j - i and s[i:j] not in res:
                res.append(s[i:j])
    return sorted(res)
print(find(s))

P47 英语单词词频统计


假设你是一名语言学家,你想要分析一篇英文文章的单词使用情况。你需要编写一个程序,读取文章并输出文章中出现频率排名前三的单词及其出现次数。

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(f"{ch[0].lower():^5}:{ch[1]:^3}次")


P49 简单数字加密


实现一个加密函数,对输入的4位数字进行加密,并输出加密结果。加密规则如下:对每一位数字都利用该数字对应的ASCII编码加上5,然后用除以10的余数代替该数字。将第一位和第四位交换,第二位和第三位交换。要求程序接收用户输入,如果是4位的整数,则进行加密操作并输出加密结果;如果输入的不是4位整数,则进行用户提示“输入不合法!”。

try:
    num = input()
    if len(str(int(num))) != 4:
        print("输入不合法!")
    else:
        encryption = ""
        for i in num:
            encryption += str((ord(i) + 5) % 10)
        print(encryption[::-1])
except:
    print("输入不合法!")


P50 食材搭配


假设你是一个美食家,现在需要编写一个函数,函数接收一个字符串作为参数,该字符串由多个食材组成,每个食材之间用"$","#"等特殊符号隔开,函数需要将这些食材两两组合起来,输出所有可能的菜式,要求食材不能重复出现。 注意:为确保输出一致,在解析出食材之后,建议先对食材排一次序再进行搭配,搭配好后排序再输出,中文本质上是利用unicode字符转换的数值排序,不是拼音序号排序。

import re
def slice_string(string):  # 中文的切片
    pattern = re.compile(r'[^\u4e00-\u9fa5]+')
    result = pattern.split(string)
    return [x for x in result if x]
def food_combination(food_list):  # 输出组合后的结果
    for i in range(len(food_list)):
        for j in range(i + 1, len(food_list)):
            print(f"{food_list[i]}+{food_list[j]}", end=" ")
str1 = input()
str2 = list(set(slice_string(str1)))
str2.sort()
food_combination(str2)


P64 传感器数据分析


下面是一个传感器采集数据文件sensor_data.in的一部分,编码格式为utf-8:
2018-02-28 01:03:16 19.3024 38.4629 45.08 2.68742
2018-02-28 01:06:16 19.1652 38.8039 46.08 2.68742
2018-02-28 01:06:46 19.175 38.8379 47.08 2.69964
其中,每行是一个读数,分别包括日期、时间、温度、湿度、光照和电压。请你编写程序输出传感器采集数据中光照部分大于47的时间和光照到sensor_data.out文件中。

fr = open('sensor_data.in', 'r', encoding='utf-8')
fw = open('sensor_data.out', 'w', encoding='utf-8')
lst = []
for line in fr:
    line = line.replace('\n', '')
    line = line.split(' ')
    if float(line[4]) > 47:
        fw.write(line[1]+' '+line[4]+'\n')
fr.close()
fw.close()


P65 简单公式计算


定义函数fun(n)完成如下功能:如果n为奇数,输出表达式​1+1/3+​…+1/n的值;如果n为偶数,输出表达式​1/2+1/4+​…+1/n的值。 编写程序接收一个正整数n(n<=1000000),并进行正确性判断,非法则输出“输入不合法!”,否则调用函数fun输出表达式计算结果,结果保留 2 位小数。

def fun(n):
    summ = 0
    if n % 2 == 0:
        for i in range(2, n + 1, 2):
            summ += float(1 / i)
        print("%.2f" % summ)
    else:
        for i in range(1, n + 1, 2):
            summ += float(1 / i)
        print("%.2f" % summ)
try:
    n = input()
    if len(n) != len(str(int(n))) or 1000000 < int(n) or int(n) <= 0:
        print("输入不合法!")
    else:
        fun(int(n))
except:
    print("输入不合法!")


P100 回文数字


编写一个Python程序,判断输入的数字是否是回文数字。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬例如,若n=1234321,则称n为一回文数;但若n=1234567,则n不是回文数。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬

x = str(input())
if x == x[::-1]:
    print("True")
else:
    print("False")


P101 酒驾判定


编写一个 Python 程序,根据输入的酒精含量阈值检查是否酒驾。

s = int(input())
if s < 20:
    print("不构成饮酒驾驶行为,可以开车,但要注意安全!")
elif 20 <= s < 80:
    print("已构成饮酒驾驶行为,请不要开车!")
elif 80 <= s:
    print("已构成醉酒驾驶行为,千万不要开车!")


P102 三角形形状检查


编写一个 Python 程序来检查三角形是等边、等腰还是普通三角形。

a = int(input())
b = int(input())
c = int(input())
if a + b <= c or a + c <= b or c + b <= a or a < 0 or b < 0 or c < 0:
    print("不构成三角形")
elif a == b == c:
    print("等边三角形")
elif a == b or a == c or b == c:
    print("等腰三角形")
else:
    print("普通三角形")


P103 水仙花判断


输入一个三位数的整数,判断是否为水仙花数。水仙花数是指一个3位数,它的每个位上的数字的3次幂之和等于它本身(例如:1^3+5^3+3^3 = 153)。

s = input()
if int(s[0])**3 + int(s[1])**3 + int(s[2])**3 == int(s):
    print("是")
else:
    print("不是")


P104 序列求和


输入两个正整数 m,n, 计算并输出m与n之间所有能被5和7整除的数和。

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


P105 计算圆周率——无穷级数法


圆周率π可以用无穷级数表示:左边的展式是一个无穷级数,被称为莱布尼茨级数(Leibniz),这个级数收敛到π/4,它通常也被称为格雷戈里-莱布尼茨级数,用以纪念莱布尼茨同时代的天文学家兼数学家詹姆斯·格雷戈里。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬编程用这个公式计算π值,输入一个小数作为阈值,当最后一项的绝对值小于给定阈值时停止计算并输出得到的π值。

dec = float(input())
PI = 0
flag = 1
i = 1
while 1 / i >= dec:
    PI = PI + flag * 1 / i
    i = i + 2
    flag = -flag
PI *= 4
print("%.8f" % PI)


P106 扑克牌游戏


本题限定用以下方法打乱序列中的元素random.shuffle()几个人用一副扑克牌玩游戏,游戏过程通常有洗牌、发牌、理牌等动作,编写程序模拟游戏过程。新牌花色顺序为♠、♥、♣、♦,花色相同时按2、3、4、5、6、7、8、9、10、J、Q、K、A,最后是小王和大王,小王用'jokers'、大王用 'JOKERS'表示。按以下要求编写程序:‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬1、按顺序输出新牌 2、洗牌 3、按洗好的顺序输出洗过的牌 4、将牌轮流分给参与游戏的人,按分牌的顺序输出每个人手上的牌 5、对每个人手上的牌升序排序并输出 6、输出时,每张牌间用空格分隔

import random
people_num = int(input())
each_cards_num = int(54 / people_num)
random_num = int(input())
random.seed(random_num)
cards = [('♠2', 0), ('♠3', 1), ('♠4', 2), ('♠5', 3), ('♠6', 4), ('♠7', 5),
         ('♠8', 6), ('♠9', 7), ('♠10', 8), ('♠J', 9), ('♠Q', 10), ('♠K', 11), ('♠A', 12),
         ('♥2', 13), ('♥3', 14), ('♥4', 15), ('♥5', 16), ('♥6', 17), ('♥7', 18),
         ('♥8', 19), ('♥9', 20), ('♥10', 21), ('♥J', 22), ('♥Q', 23), ('♥K', 24), ('♥A', 25),
         ('♣2', 26), ('♣3', 27), ('♣4', 28), ('♣5', 29), ('♣6', 30), ('♣7', 31),
         ('♣8', 32), ('♣9', 33), ('♣10', 34), ('♣J', 35), ('♣Q', 36), ('♣K', 37), ('♣A', 38),
         ('♦2', 39), ('♦3', 40), ('♦4', 41), ('♦5', 42), ('♦6', 43), ('♦7', 44),
         ('♦8', 45), ('♦9', 46), ('♦10', 47), ('♦J', 48), ('♦Q', 49), ('♦K', 50), ('♦A', 51),
         ('jokers', 52), ('JOKERS', 53)]
print(f"参与游戏的人数:{people_num}")
print("新牌顺序")
for i in range(54):
    print(cards[i][0], end=' ')
print()
print("洗牌顺序")
random.shuffle(cards)
for i in range(54):
    print(cards[i][0], end=' ')
print()
print("每个人手上分到的牌")
for i in range(people_num):
    for j in range(each_cards_num):
        print(cards[i::people_num][j][0], end=' ')
    if i != people_num:
        print()
print("每个人手上排序的牌")
for i in range(people_num):
    player = cards[i::people_num]
    player.sort(key=lambda x: x[1])
    for j in range(each_cards_num):
        print(player[j][0], end=' ')
    if i != people_num:
        print()


P107 凯撒密码——加密


在密码学中,凯撒密码是一种最简单且最广为人知的加密技术。“恺撒密码”据传是古罗马恺撒大帝用来保护重要军情的加密系统。它是一种替换加密的技术,明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。例如,当偏移量是3的时候,所有的字母A将被替换成D,B变成E,以此类推,小写字母和数字也一样处理,其他字符不作任何改变.‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬例如这样一条指令:'All roads lead to Rome.' 用恺撒密码加密后就成为:‘Doo urdgv ohdg wr Urph.’编写一个程序实现凯撒加密:输入一个字符串,对字符串中的字母和数字进行加密(规定加密偏移量为3,即后移三位),并输出加密后的字符串。

str1 = input()
for i in range(0, len(str1)):
    if "X" <= str1[i] <= "Z" or "x" <= str1[i] <= "z":
        print(chr(ord(str1[i])-23), end="")      # ord是字符转ASCII,chr是ASCII转字符
    elif "7" <= str1[i] <= "9":
        print(chr(ord(str1[i])-7), end="")
    elif str1[i] == " ":
        print(" ", end="")
    else:
        print(chr(ord(str1[i])+3), end='')


P108 素数筛选


一个正整数若只能被1和自身整除,编写程序,输入一系列正整数,筛选出其中的素数。

def find(a):
    i = 2
    while i < a:
        if a % i == 0:
            return False
        else:
            i += 1
    return True
num = input().split()
for x in num:
    number = int(x)
    if number > 1 and find(number):
        print(number, end=' ')


P109 日期计算


输入一个日期,输出这个日期是这一年的第几天

year, month, day = map(int, input().split('-'))
many = 0
months = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
if 1 <= month <= 12:
    many = months[month - 1]
many += day
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
    leap = 1
else:
    leap = 0
if leap == 1 and month > 2:
    many += 1
print(many)


P111 摩斯密码翻译器


摩斯密码(morse code),又称摩斯电码、摩尔斯电码(莫尔斯电码),是一种时通时断的信号代码,通过不同的信号排列顺序来表达不同的英文字母、数字和标点符号;通信时,将英文字母等内容翻译成摩斯电码(摩尔斯电码)进行传输,收到摩斯密码(莫尔斯电码)后,对电码进行反翻译,得到通信的实际内容,达到加密通信内容的目的。 本摩斯密码(摩尔斯电码)翻译器,只对字符,数字,标点进行翻译,不区分大小写,其它内容自动忽略;摩斯密码解密时,可接受空格分隔、“/”分隔的摩斯密码,其它字符也自动忽略。 摩斯密码表_摩斯密码对照表:

str1 = str.upper(input())
morse = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
digit = ['-----', '.----', '..---', '...--', '....-', '.....', '-....', '--...', '---..', '----.']
punctuation = {'.': '.-.-.-', ':': '---...', ',': '--..--', ';': '-.-.-.', '?': '..- -..', '=': '-...-', "'": '.----.', '/': '-..-.', '!': '-.-.--', '-': '-....-', '_': '..--.-', '"': '.-..-.', '(': '-.--.', ')': '-.--.-', '$': '...-..-', '&': '·-···', '@': '.--.-.', ' ': ''}
for ch in str1:
    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=" ")


P112 字符统计


(1) 将字符串转换成列表;(2) 输入随机种子x,两个正整数m和n,要求: n > m,且 n 小于整个列表长度;(3) 设置随机种子,使用shuffle函数将列表顺序打乱;(4) 统计输出m,n区间内,出现次数最多的前5个字符和次数。

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


P113 集合操作


(1) 将字符串转换成列表lt;(2) 输入随机种子x,四个正整数m1、n1、m2和n2,要求: n1 > m1,n2 > m2 且 n1,n2 小于整个列表长度;(3) 设置随机种子,使用shuffle函数将列表顺序打乱;(4) 切片列表,设lt1 = lt[m1:n1],lt2 = lt[m2:n2];(5) 统计并输出lt1,lt2中分别出现了多少个不同的字符;(6) 输出在lt1和lt2同时出现的字符;(7) 出现在lt1但没在lt2中出现的字符。说明:为确保和输出用例一致,你需要对筛选出的字符做排序。

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


P114 身份证有效性判断


编程实现功能:用户输入一个身份证号,校验其是否是合法的身份证号码,程序的校验项为:‪‪‪‪‪‪‪‪‪‪‪‪‪‪‪‪‪‫‪‪‪‪‪‪‪‪‪‪‪(1)输入长度是否合法(2)输入数据校验位是否合法(3)输入数据中年月日范围是否合法(年份应该在2024年之前,每个月的日期应该考虑),考虑闰年。如身份证号码不合法输出 '身份证校验错误', 如身份证号码合法则分别在3行中输出'身份证号码校验为合法号码'。

def check_id_number(id_number):
    # 检查长度是否合法
    if len(id_number) != 18:
        return '身份证无效'
    # 检查数据校验位是否合法
    check_sum = 0
    check_codes = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
    check_codes_dict = {0: '1', 1: '0', 2: 'X', 3: '9', 4: '8', 5: '7', 6: '6', 7: '5', 8: '4', 9: '3', 10: '2'}
    for i in range(17):
        check_sum += int(id_number[i]) * check_codes[i]
    remainder = check_sum % 11
    if id_number[-1] != check_codes_dict[remainder]:
        return '身份证无效'
    # 检查年月日范围是否合法
    year = int(id_number[6:10])
    month = int(id_number[10:12])
    day = int(id_number[12:14])
    if year < 1900 or year > 2024:
        return '身份证无效'
    if month < 1 or month > 12:
        return '身份证无效'
    if day < 1 or day > 31:
        return '身份证无效'
    if (month == 4 or month == 6 or month == 9 or month == 11) and day > 30:
        return '身份证无效'
    if month == 2:
        if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
            if day > 29:
                return '身份证无效'
        else:
            if day > 28:
                return '身份证无效'
    return '身份证有效'
id_number = input()
print(check_id_number(id_number))


P115 素数筛选


输入两个正整数m和n,筛选出m~n(包含m和n)之间所有的素数,数之间用空格分隔。素数又称质数,是指一个正整数只能被1和自身整除。

def find(a):
    i = 2
    while i < a:
        if a % i == 0:
            return False
        else:
            i += 1
    return True
m, n = map(int, input().split())
for i in range(m, n+1):
    if find(i):
        print(i, end=' ')


P116 字符统计排序


编写程序:从键盘中输入一段字符,完成以下统计并输出:(1)该段字符中总共出现了多少种不同类型的字符;(2)出现次数最多的前3个字符(只能为字母和数字,其它忽略)及次数?

s = input()
dict0 = {}
dict1 = {}
all_length = 0
for ch in s:
    dict0[ch] = dict1.get(ch)
    all_length = len(dict0)
    if ch.isalnum():
        dict1[ch] = dict1.get(ch, 0) + 1
length = len(dict1)
items = list(dict1.items())
items.sort(key=lambda x: x[1], reverse=True)
top3 = items[:3]
print(f"总共出现了{all_length}种字符")
for i in range(3):
    if i < len(top3):
        print(f"{top3[i][0]}:{top3[i][1]}次")

P117 isbn判别


编写程序,输入一个10位ISBN书号,判断是否为有效ISBN号,若是,输出有效,若不是,输出无效,并输出正确校验码的ISBN号。

b = input()
a = list(b)
he = int(a[0])*10+int(a[2])*9+int(a[3])*8+int(a[4])*7+int(a[6])*6+int(a[7])*5+int(a[8])*4+int(a[9])*3+int(a[10])*2
he = 11-(he % 11)
if int(a[12]) == he:
    print("正确")
else:
    out = b[0]+b[2]+b[3]+b[4]+b[6]+b[7]+b[8]+b[9]+b[10]+str(he)
    print("不正确")
    print("正确的应该是", end='')
    print(out)


P118 数组接雨


给定一个整形数组​​arr​​**,已知其中所有的值都是非负的,将这个数组看作一个柱子高度图,计算按此排列的柱子,下雨之后能接多少雨水。​​(​​数组以外的区域高度视为​0)**

height = [int(x) for x in input().split(',')]
n = len(height)
left, right = 0, n - 1
left_max, right_max = height[0], height[n - 1]
summ = 0
while left <= right:
    left_max = max(left_max, height[left])
    right_max = max(right_max, height[right])
    if left_max < right_max:
        summ += left_max - height[left]
        left += 1
    else:
        summ += right_max - height[right]
        right -= 1
print(summ)


P119 兔子问题


有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,且以“对”为计量单位。输入月份n,问第n个月的兔子总数是多少对?(提示:列举兔子产生的“对”数量,分析这些数量的规律然后构造表达式)。

def fun(n):
    if n <= 0:
        return
    if n == 1 or n == 2:
        return 1
    else:
        return fun(n-1) + fun(n-2)
n = int(input())
print(fun(n))

P120 青蛙跳


有一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个 n 级的台阶总共有多少种跳法(先后次序不同算不同的结果)

def jump(n):
    if n == 1:
        return 1
    elif n == 2:
        return 2
    else:
        return jump(n-1) + jump(n-2)
n = int(input())
print(jump(n))


P121 序列统计


将用户输入的多个数值(以输入为空结束)存放至列表中,并完成以下统计计算: 1、计算所有数的最大值,最小值,平均值; 2、计算中位数,中位数:在一个有序数列中位于中件位置的数,若数据个数为偶数时,中位数为中间两个数值的平均值,保持两位小数精度。

lst = []
s = input().split(' ')
for x in s:
    lst.append(float(x))
length = len(lst)
max_num = max(lst)
min_num = min(lst)
avg_num = sum(lst) / length
lst.sort()
if length % 2 == 0:
    mid_num = (lst[length // 2 - 1] + lst[length // 2]) / 2
else:
    mid_num = lst[length // 2]
print(f"最大值:{max_num}",end=',')
print(f"最小值:{min_num}",end=',')
print("平均值:%.2f" % avg_num,end=',')
print("中位数:%.2f" % mid_num,end='')


P122 峰值查找


给定一个长度为n的列表nums,请你找到峰值并返回其索引。数组可能包含多个峰值,在这种情况下,返回任何一个所在位置即可。 (1)峰值元素是指其值严格大于左右相邻值的元素。严格大于即不能有等于; (2)列表两个边界可以看成是最小

nums = []
s = input().split(' ')
for x in s:
    nums.append(float(x))
left, right = 0, len(nums) - 1
while left < right:
    mid = (left + right) // 2
    if nums[mid] > nums[mid + 1]:
        right = mid
    else:
        left = mid + 1
print(left)


P123 摩斯密码解密


已知某摩斯密码的加密规则为:将输入的英文句子转换成摩尔斯电码并输出,其中字母、数字和标点符号按编码输出(和之前OJ中的加密规则一样),若编码表里没有的字符,原样输出,且每个摩斯码之间用一个空格分隔。 

str1 = input().split(' ')
morse = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
digit = ['-----', '.----', '..---', '...--', '....-', '.....', '-....', '--...', '---..', '----.']
punctuation = {'.': '.-.-.-', ':': '---...', ',': '--..--', ';': '-.-.-.', '?': '..- -..', '=': '-...-', "'": '.----.', '/': '-..-.', '!': '-.-.--', '-': '-....-', '_': '..--.-', '"': '.-..-.', '(': '-.--.', ')': '-.--.-', '$': '...-..-', '&': '·-···', '@': '.--.-.', ' ': ''}
real_words = ""
for ch in str1:
    if ch in morse:
        real_words += chr(ord('a')+morse.index(ch))
    elif ch in digit:
        real_words += chr(ord('0') + digit.index(ch))
    elif ch in punctuation.values():
        real_words += list(punctuation.keys())[list(punctuation.values()).index(ch)]  # 通过value值寻找key值
    else:
        real_words += ch
print(real_words)


P124 公式计算


输入数正整数m,输出0! + 1! +...+m!的计算结果。

m = int(input())
result = 1
factorial = 1
for i in range(1, m + 1):
    factorial *= i
    result += factorial
print(result)


P125 寻找反素数


反素数,英文称作 emirp(prime(素数)的左右颠倒拼写),是素数的一种。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬把一个素数的阿拉伯字数字序列变成由低位向高位反写出来,得到的另一个数还是素数。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬例如素数13,反写就是31,它是另一个素数,所以13是一个反素数。这个定义排除了相关的回文素数,因为回文素数反写不是另一个数而是它本身。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬最小的几个反素数为:13, 17, 31, 37, 71, 73, 79, 97, 107, 113, 149, 157, 167, 179, 199, ...‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬编写程序,输入两个数m和n,要求n > m,输出m~n(包含m和n)之间所有的反素数,数之间用空格隔开。

def reverse_num(n):  # 数字反转
    n = int(str(n)[::-1])
    return n
def palindrome_num(n):  # 判断回文数字
    if str(n) == str(n)[::-1]:
        return True
    else:
        return False
def is_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
m, n = map(int, input().split(' '))
for i in range(m, n + 1):
    if is_prime(i) and is_prime(reverse_num(i)) and not palindrome_num(i):
        print(i,end=' ')


P126 维吉尼亚加密


编写一个程序,根据输入的密钥对输入的明文进行加密输出。

secret_key = input().lower()  # 密钥
plain_text = input()  # 明文
upper_words = []  # 大写字母组合
lower_words = []  # 小写字母组合
num_words = []  # 数字组合
for i in range(26):
    upper_letter = [chr((i + j) % 26 + 65) for j in range(26)]
    upper_words.append(upper_letter)
    lower_letter = [chr((i + k) % 26 + 97) for k in range(26)]
    lower_words.append(lower_letter)
for i in range(10):
    num_letter = [chr((i + j) % 10 + 48) for j in range(10)]
    num_words.append(num_letter)
row = 0  # 行
for ch in plain_text:
    if ch.islower():
        print(lower_words[ord(secret_key[row % len(secret_key)]) - 97][ord(ch) - 97], end='')
    elif ch.isupper():
        print(upper_words[ord(secret_key[row % len(secret_key)]) - 97][ord(ch) - 65], end='')
    elif ch.isdigit():
        print(num_words[(ord(secret_key[row % len(secret_key)]) - 97) % 10][ord(ch) - 48], end='')
    else:
        print(ch, end='')
        row -= 1
    row += 1


P127 信息脱敏


编写一个 Python 程序,读取data.in文件中的数据(utf-8编码),将其中的姓名、身份证、手机号码部分信息替换成*`进行脱敏处理,结果输出到data.out文件中。

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()


P128 csv存json格式


编写一个 Python 程序,读取movie.in(csv格式,utf-8编码) 的数据,将数据转成保存到movie.out(接送格式,utf-8编码)文件中。

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()


P129 csv文件计算


在附件salary.in中存储了员工一季度1,2,3月的收入,编写程序计算一季度的总收入,并将结果按总收入降序写至salary.out文件。

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()


P130 信息存csv文件


请将inf.in文件(utf-8编码)的个人身份信息以csv格式存到到inf.out文件(以utf-8编码)。

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()

 

P131 歌唱比赛统计


某歌唱比赛有10位评委,选手得分规则为去掉一个最高分和最低分,取其余的平均分。选手们的成绩已经存放至sing.in文件(utf-8编码),请统计各位选手的得分,保留小数点后两位,并将成绩以降序排序输出至sing.out文件(utf-8编码)。 注意:测试用例中,选手数量可能与样例不同。

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')

 

P132 天气数据筛选


文件weather.in(csv格式,utf-8编码)存放了一段时间的天气数据,请筛选出其中天气为阴,且最低温大于等于1℃的数据,将其csv格式,utf-8编码存储至weather.out文件。 注意:测试用例中数据条数和样例可能不同。

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)

 

 P133 json格式转存csv文件


文件movie.in中以json格式存放了一些电影数据,你可以通过json库很容易将数据读入成Python内部对象,请观察一下代码的运行结果。

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['时长(分钟)']])


P134 销售数据统计


在sale.in文件存储了员工一年中每个月的销售数据(csv格式,utf-8编码),请读取该文件,并计算每位员工的年销售综合,再按年度销售综合降序排序后写到sale.out文件(csv格式,utf-8编码)。

fr = open('sale.in', 'r', encoding='utf-8')
fw = open('sale.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()


 

  • 30
    点赞
  • 173
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

arrest404

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值