[英]Best approach to this question using python
我是 python 的新手并练习了一些问题。 无法针对以下问题优化我的解决方案。
问题陈述:根据词频对句子中的词进行编码,并返回词的排名和编码值。
示例:输入字符串 --> 'aaa bb ccc aaa bbb bb cc ccc ccc bb ccc bbb'
预期 output --> 3|2|1|3|4|2|5|1|1|2|1|4
解释:- 因为 'aaa' 在原始字符串中出现了 2 次, 'ccc' 出现了 4 次, 'bb' 出现了 3 次,因此它们根据频率获得排名。 以这种方式,'ccc' 等级为 1,'bb' 等级为 2,'ccc' 等级为 3。因此结果如上所述。
下面是我的 python 代码,但无法优化。 有人可以帮忙吗。
def testing(s):
ht = {}
new_strs = strs.split()
print(new_strs)
for i in new_strs:
if i in ht:
ht[i] += 1
else:
ht[i] = 1
print(ht)
temp = list(map(list, sorted(ht.items(), key=lambda v: v[1], reverse=True)))
print(temp)
for k,v in enumerate(temp):
temp[k].append(k+1)
print(temp)
final = []
for j in new_strs:
for t in temp:
if t[0] == j:
final.append(str(t[2]))
return '|'.join(final)
strs = 'aaa bb ccc aaa bbb bb cc ccc ccc bb ccc bbb'
result = testing(str)
print(result)
下面是我从这段代码中得到的结果。
['aaa', 'bb', 'ccc', 'aaa', 'bbb', 'bb', 'cc', 'ccc', 'ccc', 'bb', 'ccc', 'bbb']
{'aaa': 2, 'bb': 3, 'ccc': 4, 'bbb': 2, 'cc': 1}
[['ccc', 4], ['bb', 3], ['aaa', 2], ['bbb', 2], ['cc', 1]]
[['ccc', 4, 1], ['bb', 3, 2], ['aaa', 2, 3], ['bbb', 2, 4], ['cc', 1, 5]]
3|2|1|3|4|2|5|1|1|2|1|4
预先感谢您的帮助。
通过计数,您的代码很好。 从您的for j
循环开始,我完全不确定您认为这应该如何工作。
您需要遍历字符串中的给定单词——一个循环,而不是嵌套循环。 对于输入中的每个单词,将其频率放入结果中。
for word in new_strs:
final.append(str(ht[word]))
print(final)
通过该替换,您的 output 是:
['2', '3', '4', '2', '2', '3', '1', '4', '4', '3', '4', '2']
2|3|4|2|2|3|1|4|4|3|4|2
正如Robert
已经指出的那样,您的代码中还有其他错误。 特别是,您将类型传递给 function。 如果您打算str
成为一个变量,请不要这样做。 当您使用 Python 定义的名称(类型字符串)作为变量时,会损坏名称空间,并且会发生奇怪的事情。
这有点令人费解,但会这样做。
我认为这是 go 的最佳方法,即将排名逻辑分成 class。
from collections import Counter
class Ranker:
def __init__(self, items):
self._item_counts = Counter(items)
self._ranks = list(set(i[1] for i in Counter(items).most_common()))[::-1]
def __getitem__(self, item):
return self._ranks.index(self._item_counts[item]) + 1
if __name__ == '__main__':
strs = 'aaa bb ccc aaa bbb bb cc ccc ccc bb ccc bbb aaa'.split()
r = Ranker(strs)
print('|'.join([str(r[s]) for s in strs]))
# 2|2|1|2|3|2|4|1|1|2|1|3|2
正如评论中指出的那样,而不是
strs = '...' # This is a global variable
def testing(s):
... # Body of testing function that never references the local `s` variable
你应该有
def testing(strs):
... # Body of testing uses `strs` as before
没有理由对ht.values()
进行排序,因此可以完全取消分配给temp
的操作。
当您遍历new_strs
时,您要做的就是创建一个列表,其中包含 new_strs 中元素的计数。 这是您存储在ht
字典中的内容。 所以
for s in new_strs:
final.append(ht[s])
现在 final 是一个列表,其中包含字符串在原始字符串中出现的次数。 您可以像现在一样返回。
我建议进行这些小改动并查看它是否有效。 然后,一旦 function 按您的预期工作,就有很多可以清理的地方。
您可以使用defaultdict而不是常规字典。 您可以使用列表推导来构建final
列表。
from collections import defaultdict
def testing(strs):
ht = defaultdict(int)
new_strs = strs.split()
for s in new_strs:
ht[s] += 1 # if `s` is not in ht, the default 0 is used.
final = [strs(ht[s]) for s in new_strs]
return '|'.join(final)
字符串连接方法可以使用生成器,因此不需要创建中间final
变量。 最后两行可以写成一行
return '|'.join(strs(ht[s]) for s in new_strs)
collections 模块有一个计数器集合,它可以准确计算列表中的内容。 您可以将此 function 编写为:
from collections import Counter
def testing(strs):
new_strs = strs.split()
ht = Counter(new_strs)
return '|'.join(str(ht[s]) for s in new_strs)
自从最初提出这个问题以来,这个问题已经发生了变化。 所以这是一个新的答案。
def testing(strs):
new_strs = strs.split()
ht = Counter(new_strs)
ranks = rank(sorted(list(dict(ht).items()), key = lambda t: t[1], reverse=True))
ranks_dict = dict(ranks)
return '|'.join(str(ranks_dict[s]) for s in new_strs
您只需要rank
function,它采用 (value, score) 的元组的排序列表并返回 (value, rank) 的列表
def rank(tuples):
current_score = tuples[0][1]
current_rank = 1
ties = 0
ranks = []
for tup in tuples:
if tup[1] == current_score:
ties += 1
else:
current_rank = current_rank + ties
ties = 1
ranks.append((tup[0], current_rank))
current_score = tup[1]
return ranks
请注意,我正在计算两个出现相同次数的单词,因为它们具有相同的排名。 在您的示例中,您将它们设置为不同的等级,但没有提供确定哪个是哪个的方法。 我希望这足以让你走上正轨。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.