2 回答
TA贡献1862条经验 获得超6个赞
words = []
while True:
y = input()
if y == "###":
break
words.extend(y.lower().split())
from collections import Counter
Counter(words).most_common(1)
整个代码可以压缩为以下一种格式:
Counter(y.lower() for x in iter(input, '###') for y in x.split()).most_common(1)
例如。
>>> sys.stdin = StringIO.StringIO("""Here is a line like sparkling wine
Line up now behind the cow
###""")
>>> Counter(y.lower() for x in iter(input, '###') for y in x.split()).most_common(1)
[('line', 2)]
由于每个请求,而没有任何import小号
c = {} # stores counts
for line in iter(input, '###'):
for word in line.lower().split():
c[word] = c.get(word, 0) + 1 # gets count of word or 0 if doesn't exist
print(max(c, key=c.get)) # gets max key of c, based on val (count)
不必再次通过字典来查找最大单词,请在进行操作时始终对其进行跟踪:
c = {} # stores counts
max_word = None
for line in iter(input, '###'):
for word in line.lower().split():
c[word] = c.get(word, 0) + 1 # gets count of word or 0 if doesn't exist
if max_word is None:
max_word = word
else:
max_word = max(max_word, word, key=c.get) # max based on count
print(max_word)
添加回答
举报
