2 回答

TA貢獻1862條經(jīng)驗 獲得超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)
添加回答
舉報