测试python-cod的正确方法

2024-05-03 05:37:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的模求幂代码,我想在函数中测试几行代码。 一行是:

temp = square(temp)

但python抱怨没有定义全局名“square”。另外,我该如何对这条线进行基准测试

^{pr2}$

我还需要把它写入函数吗?在

import math
import timeit
def int2baseTwo(x):
    """x is a positive integer. Convert it to base two as a list of integers
    in reverse order as a list."""
    # repeating x >>= 1 and x & 1 will do the trick
    assert x >= 0
    bitInverse = []
    while x != 0:
        bitInverse.append(x & 1)
        x >>= 1
    return bitInverse

def square(a):
    return a ** 2

def modExp(a, d, n):
    """returns a ** d (mod n)"""
    assert d >= 0
    assert n >= 0
    base2D = int2baseTwo(d)
    #print 'base2D = ', base2D
    base2DLength = len(base2D)
    #print 'base2DLength = ', base2DLength
    modArray = []
    result = 1
    temp = 1
    for i in range(0, base2DLength):
        if i == 0:
            temp = a
            continue
        print(timeit.timeit("temp = square(temp)", setup="from __main__ import modExp"))
        if base2D[i] == 1:
            temp = temp * a
    ret = temp % n
    return ret

if __name__=="__main__":
    print(timeit.timeit("modExp(1000,100,59)", setup="from __main__ import modExp"))

Tags: 代码importreturnifmaindefasserttemp