python 3 : Integer not repeated

标签 python python-3.x

在随机整数列表中,整数在列表中重复,如何从列表中打印出根本不重复的整数?

我试图通过编写以下程序来解决这个问题:

K = int(input())

room_list = list(input().split())

room_set = set(room_list)

for i in room_set:

    count = room_list.count(i)

    if count == 1:
        i = int(i)
        print(i)
        break

K 是列表中元素的数量。

当我尝试运行上述程序时,它在元素较少的情况下运行良好,但是,当使用具有(比如 825)个元素的列表对其进行测试时,程序超时。

请帮我优化上面的代码。

最佳答案

列表中重复次数为 1 的元素将是您的答案。

from collections import Counter
a = [1,1,1,2,2,3,4,5,5]
c = Counter(a) # O(n)
x = [key for key, val in c.items() if val == 1]
print(x)

输出:

[3,4]

Counter class通过遍历列表一次来创建元素和重复项的字典,这需要时间 O(n) 并且每个元素的访问需要 O(1) 时间。

每次在列表上调用时,列表的计数函数都会迭代。在您的情况下需要 O(n^2) 时间。

关于 python 3 : Integer not repeated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53033198/

相关文章:

python - 为什么 Python linecache 影响回溯模块而不是常规回溯?

python - 错误 flask-sqlalchemy NameError : global name 'joinedload' is not defined

python - 将随机森林预测作为列添加到测试文件中

python - 如何根据列中的条件进行计算?

python - 使用电子邮件模块(PYTHON)解析来自 poplib 的电子邮件内容

python - 在 Python 中生成用户名

python - 在python中转换pandas dataframe datetime格式

Python heapify() 时间复杂度

Python:如何在操作系统中打开文件时写入文件

python-3.x - Python Azure sdk - 启用磁盘加密