程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

如何让我的 python 程序更快?CSES练习

发布于2023-08-22 01:44     阅读(1156)     评论(0)     点赞(13)     收藏(1)


所以我正在尝试解决这个 CSES 练习:https://cses.fi/problemset/task/1621/

这是练习的屏幕截图

这是我的代码:

n = int(input())
input_line = input()

integers = list(map(int, input_line.split()))


while len(integers) != 0:
    integers = [element for element in integers if element != integers[0]]
    count= count + 1

print(count)

我的代码超出了许多测试的时间限制(有大量数据需要处理的测试)。

我尝试优化我的代码但没有任何效果,它太慢了,


解决方案


当您应该使用集合时,您不必要地解析字符串并不断构建新列表,集合会自动将数据删除重复为不同的值

# discard first line, since not necessary unless doing input validation
_ = input()
# print the length of distinct space separated strings in the second line 
print(len(set(input().split())))


所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/2013347/6ae571e3dbcf9080873e/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

13 0
收藏该文
已收藏

评论内容:(最多支持255个字符)