【问题标题】:Python Array effiencyPython 数组效率
【发布时间】:2017-07-25 19:01:50
【问题描述】:

我正在解决 coderfights 中的一个小问题:

注意:如果数组是 [1,1,1,2,3] 它也是 False,因为它有重复。

我的程序正在完全运行,但是在包含 5,000 个条目的测试数组上,它不适合 4 秒的窗口来完成。

我的代码:

def almostIncreasingSequence(s):
l = len(s); 
R1 = [] #RESULT AFTER 1st test
R2 = [] #RESULT AFTER 2nd test
T2 = [] #All true, to remove false positives

       #TEST ONE 1 BY 1
for n in range(0,l):
    one = s[:];
    one.pop(n)        
    k = one[:];
    if sorted(k)==k:
        R1.append("T")
        T2.append(k)
    #else:
        R1.append("F")

        #TEST 2, REMOVE FALSE POSITIVE DUPLICATES
if "T" in R1:
   # print("will go throught",T2)

    secondTEST = len(T2)
    for n in range(0,secondTEST):
        #print("Running False Positive test for array # ",n)
        duplicates = []
        duplicates = T2[n]
        if (len(duplicates) != len(set(duplicates))):
           # print("DUPLICATE FOUND IN",T2[n])
            #if found add F to R2
            R2.append("F")
        else:
           # print("no duplicate found in, so TRUE ",T2[n])
            R2.append("T")
        #tf.append("F")
if "T" in R2:
    return True
else:
    return False

我所做的是: 第一个循环删除了 1 个元素,检查它是否适用于所有情况。如果为 True,则保存数组以对其进行第二次测试。当循环结束时,如果有数组作为 True 传递,第二次测试通过检查其中是否有重复数字来消除误报。如果他们做它的误报,如果没有它的真。

最后我在第二次测试后得到数组,例如 [T,F,F] 如果它包含 T 则其中一个数组不是误报。

我的问题是如何提高我的方法的性能?如果为 false,我尝试不将“F”写入数组,但在不到 4 秒的时间内通过 5.000 个数组仍然不会提高性能。

【问题讨论】:

  • 你能解释一下为什么[1,1,2,3] 的计算结果为假吗?如果您删除其中一个 1,则它是严格排序的。
  • 现在已编辑,我错过了数组中的一个额外的 1。感谢您的关注!

标签: python arrays performance


【解决方案1】:

提高性能的最有效方法是使用更好的算法。试试这样的[这是伪代码,你必须自己编写实际的 Python]

# If a sequence is not strictly increasing then there will be a point at 
#   which a[n] >= a[n+1].  We'll call that a reversal.
Scan the array for a reversal
If you find a reversal, 
  #  At this point you have an option of removing element n, 
  #   or removing element n+1. Try them one at a time:
  if  a[n-1] < a[n+1] then check the results of removing element n
     call another method that checks for strict ordering for the rest 
       of the array. [i.e. n+1 .. array.size] 
     If that method returns true, then return true
                 else fall thru to next check

# if you get here, removing element n won't work:
   if a[n] < a[n+2] then check the results of removing element n+1
       call the method that checks for strict ordering for the rest 
         of the array. [i.e. n+2 .. array.size]
       return whatever value it returns
   else removing element n+1 won't work either
     return false

# if you get here, you didn't find any reversals.
return true

请注意,实际上不需要删除元素,因为问题只是确定您是否可以根据需要删除它。将输入视为不可变既可以提高性能,又可以通过“试用删除”消除引入错误的机会。

您必须非常小心地编写代码以避免数组末端出现边界条件。

【讨论】:

    猜你喜欢
    • 2016-09-09
    • 2013-03-13
    • 2011-08-29
    • 2012-05-27
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    相关资源
    最近更新 更多