python - 减少时间消耗

标签 python list python-2.7

我正在为 this problem 编写代码:

Given an array A having N elements. Find total number of pairs (i,j) such that j < i and Aj = Ai.

这是我的代码:

raw_input()

l = list(map(int, raw_input().split()))

count = 0

for a in range(len(l)):
    count = count + l[a+1:].count(l[a])

print(count)

但不幸的是,该代码花费了很多时间。您有什么建议可以帮助我减少时间消耗吗?我的意思是,如何减少 for 循环中消耗的时间。我觉得 list.count 方法需要很多时间,所以你有什么想法可以替换它。

最佳答案

您可以通过使用比 .count() 更快的方式检查成员资格来加快速度。例如,dict 查找速度非常快:

from collections import defaultdict

raw_input()

l = list(map(int, raw_input().split()))

keys = defaultdict(list)

for i, v in enumerate(l):
    keys[v].append(i)

for value, keys in keys.items():
    print("Value %d appears at indices %s." % (k, ", ".join(keys)))

然后你只需要计算对的数量。

关于python - 减少时间消耗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36402723/

相关文章:

python - 为什么 Python 中同时存在 sre 和 re 模块?

python - Pandas pd.Grouper 和每组的顺序日期差异

python - 从 python 列表中进行窗口选择

python - 如何检查列表元素是否在另一个列表中但也在同一索引处

Python Panda 根据多列计算出现次数

python - 如何在python中将局部变量从一个cgi传递到另一个cgi

css - 在 div 中垂直居中列表

java - 更改列表中的项目并排序然后列出

python - 总结 python 中的嵌套字典值

python - 有没有更优雅的方法用 Python 编写这个?