背景
我正在研究HackerRank問題Word Order。任務是
閱讀以下輸入
stdin4 bcdef abcdefg bcde bcdef生成反映以下內容的輸出:
- 第一行的唯一詞數
- 每個唯一單詞的出現次數 示例:
3 # Number of unique words 2 1 1 # count of occurring words, 'bcdef' appears twice = 2
問題
我撰寫了兩個解決方案,第二個通過了初始測驗但由于超出時間限制而失敗。第一個也可以,但我對輸出進行了不必要的排序(雖然會出現時間限制問題)。
筆記
- 在第一個解決方案中,我對值進行了不必要的排序,這在第二個解決方案中已修復
- 我渴望更好地(正確地)使用標準 Python 資料結構、串列/字典理解——我特別渴望收到一個不匯入任何附加模塊的解決方案,
import os除非需要。
代碼
import os
def word_order(words):
# Output no of distinct words
distinct_words = set(words)
n_distinct_words = len(distinct_words)
print(str(n_distinct_words))
# Count occurrences of each word
occurrences = []
for distinct_word in distinct_words:
n_word_appearances = 0
for word in words:
if word == distinct_word:
n_word_appearances = 1
occurrences.append(n_word_appearances)
occurrences.sort(reverse=True)
print(*occurrences, sep=' ')
# for o in occurrences:
# print(o, end=' ')
def word_order_two(words):
'''
Run through all words and only count multiple occurrences, do the maths
to calculate unique words, etc. Attempt to construct a dictionary to make
the operation more memory efficient.
'''
# Construct a count of word occurrences
dictionary_words = {word:words.count(word) for word in words}
# Unique words are equivalent to dictionary keys
unique_words = len(dictionary_words)
# Obtain sorted dictionary values
# sorted_values = sorted(dictionary_words.values(), reverse=True)
result_values = " ".join(str(value) for value in dictionary_words.values())
# Output results
print(str(unique_words))
print(result_values)
return 0
if __name__ == '__main__':
q = int(input().strip())
inputs = []
for q_itr in range(q):
s = input()
inputs.append(s)
# word_order(words=inputs)
word_order_two(words=inputs)
uj5u.com熱心網友回復:
沒有任何匯入,您可以通過以下方式計算唯一元素
len(set(words))
并計算它們的出現次數
def counter(words):
count = dict()
for word in words:
if word in count:
count[word] = 1
else:
count[word] = 1
return count.values()
uj5u.com熱心網友回復:
那些嵌套回圈在性能方面非常糟糕(它們使您的演算法成為二次型)并且非常不必要。您可以在單次迭代中獲得所有計數。您可以使用普通dict或專用的collections.Counter:
from collections import Counter
def word_order(words):
c = Counter(words)
print(len(c))
print(" ".join(str(v) for _, v in c.most_common()))
顯示 Counter 及其方法作業原理的“手動”實作:
def word_order(words):
c = {}
for word in words:
c[word] = c.get(word, 0) 1
print(len(c))
print(" ".join(str(v) for v in sorted(c.values(), reverse=True)))
# print(" ".join(map(str, sorted(c.values(), reverse=True))))
uj5u.com熱心網友回復:
您可以使用Counterthen 列印輸出,如下所示:
>>> from collections import Counter
>>> def counter_words(words):
... cnt = Counter(words)
... print(len(cnt))
... print(*[str(v) for k,v in c.items()] , sep=' ')
>>> inputs = ['bcdef' , 'abcdefg' , 'bcde' , 'bcdef']
>>> counter_words(inputs)
3
2 1 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/311473.html
下一篇:Python中的串列和索引
