期末测验: 课程水平综合测验 (第10周)

期末测验: 课程水平综合测验 (第10周)

无空隙回声输出

描述
获得用户输入,去掉其中全部空格,将其他字符按收入顺序打印输出。
输入输出示例
输入
Alice + Bob
输出

Alice+Bob

【我的答案】

s = input()
s = s.replace(' ', '')
print(s)

【参考代码】

txt = input()
print(txt.replace(" ", ""))

文件关键行数

描述
关键行指一个文件中包含的不重复行。关键行数指一个文件中包含的不重复行的数量。
统计附件文件中与关键行的数量。
输入输出示例
此处仅示例输出格式。
输入 输出
示例 1
共99关键行

【我的答案】

with open('latex.log', 'r', encoding='utf-8') as f:
    rows_set = set(f.readlines())
    print('共{}关键行'.format(len(rows_set)))

【参考代码】

f = open("latex.log")
ls = f.readlines()
s = set(ls)
print("共{}关键行".format(len(s)))
# 记住:如果需要"去重"功能,请使用集合类型。

字典翻转输出

描述
读入一个字典类型的字符串,反转其中键值对输出。
即,读入字典key:value模式,输出value:key模式。
输入格式
用户输入的字典格式的字符串,如果输入不正确,提示:输入错误。
输出格式
给定字典d,按照print(d)方式输出
输入输出示例
输入 输出
示例 1
{“a”: 1, “b”: 2}
{1: ‘a’, 2: ‘b’}

【我的答案】

s = input()
try:
    dict_1 = eval(s)
    dict_2 = dict(zip(dict_1.values(), dict_1.keys()))
    print(dict_2)
except:
    print('输入错误')

【参考代码】

s = input()
try:
    d = eval(s)
    e = {}
    for k in d:
        e[d[k]] = k
    print(e)
except:
    print("输入错误")

《沉默的羔羊》之最多单词

描述
附件是《沉默的羔羊》中文版内容,请读入内容,分词后输出长度大于2且最多的单词。
如果存在多个单词出现频率一致,请输出按照Unicode排序后最大的单词。
输入格式
文件
输出格式
字符串
输入输出示例
仅提供一个输出示范样例。
输入 输出
示例 1

羔羊

【我的答案】

import jieba
with open('沉默的羔羊.txt', 'r', encoding='utf-8') as f:
    txt = f.read()
    words = jieba.lcut(txt)
    counts = {}
    for word in words:
    # 过滤长度为1的单词
        if len(word) == 1:
            continue
        else:
            counts[word] = counts.get(word, 0) + 1

【参考代码】

import jieba
f = open("沉默的羔羊.txt")
ls = jieba.lcut(f.read())
# ls = f.read().split()
d = {}
for w in ls:
    d[w] = d.get(w, 0) + 1
maxc = 0
maxw = ""
for k in d:
    if d[k] > maxc and len(k) > 2:
        maxc = d[k]
        maxw = k
    if d[k] == maxc and len(k) > 2 and k > maxw:
        maxw = k
print(maxw)
f.close()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章