python - 提高数组操作的性能
问题描述
我正在尝试解决codechef上的这个问题陈述。简而言之,问题陈述是:每次更新数组'q'次后,找出具有'n'个元素的数组的值(即将解释)。
数组的值是指数组中连续元素的绝对差之和。例如
array = [1,2,3,4,5]
value(array) = abs(1-2) + abs(2-3) + ... + abs(4-5)
我正在学习 python(第 3 天)并尝试使用以下 python 代码解决问题。
def update(arr,find,replace):
for i in range(len(arr)):
if arr[i]==find:
arr[i]=replace
def value(arr):
sum = 0
for i in range(len(arr)-1):
sum = sum + abs(arr[i]-arr[i+1])
return sum
test_case = int(input())
while test_case > 0 :
n,q = map(int,input().split(" "))
array = list(map(int,input().split()))
for i in range(q):
x,y = map(int,input().split(" "))
update(array,x,y)
print(value(array))
test_case -= 1
这段代码,当我在我的机器上运行时,会为自定义测试用例(即使输入很大)产生正确的结果,但在站点上超过了时间限制。有什么方法可以优化代码以适应给定的约束……时间复杂度:< 2 秒,大小:50000 字节?
解决方案
两个潜在的加速(未经测试):
def value(arr):
return sum(abs(arr[i]-arr[i+1]) for i in range(len(arr)-1))
# in general, avoid using built-in names for variable names also...
和:
def update(arr,find,replace):
for i in range(arr.count(find)):
arr[arr.index(find)]=replace
# find the specific replacements and replace vs
# iterating the entire list
在 Python 中:
- 内置函数通常比你自己写的要快;
- 理解通常比传统
for
循环更快; - 查找特定替换比遍历整个列表更快。
推荐阅读
- ios - 将 Objective-C 委托方法与 swift 文件混合
- angular - 如何将 merge 和 fromEvent 运算符导入 Angular 6、rxjs 6.2.0?
- sorting - 如果在范围内,则按不同字段进行条件 ElasticSearch 排序
- javascript - Javascript:将对象数组过滤成两个
- c++ - 来自 lambda 的结构中的 C++ 变量
- c - 下面如何完成多维数组的指针运算?
- c# - Log4Net 如何在没有时间的情况下记录纯文本
- android - 从 Android 设备中提取 db 文件的速度有多快?
- excel - 在PPT中复制粘贴多个excel范围的宏
- php - 在 Laravel Eloquent 模型中使用特殊的联合函数