期末测验
程序设计考试题
无空隙回声输出
获得用户输入,去掉其中全部空格,将其他字符按收入顺序打印输出。
参考答案
txt = input()
print(txt.replace(" ", ""))
最优解
print(input().replace(' ',''))
文件关键行数
关键行指一个文件中包含的不重复行。关键行数指一个文件中包含的不重复行的数量。
统计附件文件中与关键行的数量。
参考答案
f = open("latex.log")
ls = f.readlines()
s = set(ls)
print("共{}关键行".format(len(s)))
答案解析
记住:如果需要"去重"功能,请使用集合类型。
字典翻转输出
读入一个字典类型的字符串,反转其中键值对输出。
即,读入字典 key:value 模式,输出 value:key 模式。
用户输入的字典格式的字符串,如果输入不正确,提示:输入错误。
给定字典 d,按照 print(d) 方式输出
参考答案
s = input()
try:
d = eval(s)
e = {}
for k in d:
e[d[k]] = k
print(e)
except:
print("输入错误")
最优解
try:
a = eval(input())
print(dict(zip(a.values(), a.keys())))
except:
print('输入错误')
《沉默的羔羊》之最多单词
附件是《沉默的羔羊》中文版内容,请读入内容,分词后输出长度大于等于 2 且出现频率最多的单词。
如果存在多个单词出现频率一致,请输出按照 Unicode 排序后最大的单词。
参考答案
import jieba
f = open("沉默的羔羊.txt", encoding='utf-8')
ls = jieba.lcut(f.read())
d = {}
for w in ls:
if len(w) >= 2:
d[w] = d.get(w, 0) + 1
maxc = 0
maxw = ""
for k in d:
if d[k] > maxc :
maxc = d[k]
maxw = k
elif d[k] == maxc and k > maxw:
maxw = k
print(maxw)
f.close()
最优解
import jieba
with open("沉默的羔羊.txt") as f:
txt = f.read()
words = jieba.lcut(txt)
counts = {}
for word in words:
if len(word) == 1:
continue
else:
counts[word] = counts.get(word,0) + 1
list = list(counts.items())
list.sort(key = lambda x:x[1],reverse = True)
print(list[0][0])