基本 Python 算法压力测试

Basic Python Algorithm Stress Test

嗨,我正在使用 python 学习算法的基础知识,这是我的第一个压力测试脚本(我对 python 还是个新手)。

当我 运行 测试变量 fast 和结果都打印为 0 时,我包含的随机数生成器似乎没有为函数 mpp 和 mppf 创建数字以供使用,要么或者他们没有将结果分配给相关变量,因此变量仍然 = 0 并且循环继续打印 '0 0 OK'

我没有收到任何错误,只是我的脚本没有按照我的要求执行!

  import random
    result = 0
    fast = 0

    while result == fast:
        if __name__ == '__main__':
            n = (random.randint(2, 11))
            a = list(random.randint(0, 99999) for r in range(n))
            assert (len(a) == n)

            def max_pairwise_product(n, a):
                global result
                for i in range(0, n):
                    for j in range(i + 1, n):
                        if a[i] * a[j] > result:
                            result = a[i] * a[j]
                return result


            def max_pairwise_product_fast(n, a):
                global fast
                max_index1 = -1
                for i in range(n):
                    if max_index1 == -1 or a[i] > a[max_index1]:
                        max_index1 = i

                max_index2 = -1
                for i in range(n):
                    if i != max_index1 and (max_index2 == -1 or a[i] > a[max_index2]):
                        max_index2 = i
                fast = a[max_index1] * a[max_index2]
                return fast

            print(fast, result, "OK")
    else:
        print("Wrong Answer")

我认为这似乎有效:

import random
def max_pairwise_product_fast(n, a):
      global fast
      max_index1 = -1
      for i in range(n):
          if max_index1 == -1 or a[i] > a[max_index1]:
              max_index1 = i

      max_index2 = -1
      for i in range(n):
          if i != max_index1 and (max_index2 == -1 or a[i] > a[max_index2]):
              max_index2 = i
      fast = a[max_index1] * a[max_index2]
      return fast

def max_pairwise_product(n, a):
            global result
            for i in range(0, n):
                for j in range(i + 1, n):
                    if a[i] * a[j] > result:
                        result = a[i] * a[j]
            return result

result = 0
fast = 0

while result == fast:
    if __name__ == '__main__':
        n = (random.randint(2, 11))
        result=0;fast=0
        a = list(random.randint(0, 99999) for r in range(n))
        assert (len(a) == n)
        result = max_pairwise_product(n, a)

        fast=max_pairwise_product_fast(n, a)
        print(fast, result, "OK")
    else:
        print("Wrong Answer")

我不知道您的代码应该做什么,但现在看来 运行。 您不应该将定义的函数保留在循环中。

希望对您有所帮助。