Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何进一步优化计算所有交叉和?_Python_Python 3.x_Optimization - Fatal编程技术网

Python 如何进一步优化计算所有交叉和?

Python 如何进一步优化计算所有交叉和?,python,python-3.x,optimization,Python,Python 3.x,Optimization,昨天我有一些空闲时间,不知怎么的,我想计算交叉总和。 我的目标是把所有的总和计算成一个给定的数字n。别问为什么——这只是为了好玩和学习。 对于n=11,我希望我的结果是这样的:[1,2,3,4,5,6,7,8,9,1,2] 这是我的代码: def dynamicCheckSumList(upperLimit): dynamicChecksumList = [] for i in range(0, 10): dynamicChecksumList.append(i)

昨天我有一些空闲时间,不知怎么的,我想计算交叉总和。 我的目标是把所有的总和计算成一个给定的数字n。别问为什么——这只是为了好玩和学习。 对于n=11,我希望我的结果是这样的:[1,2,3,4,5,6,7,8,9,1,2]

这是我的代码:

def dynamicCheckSumList(upperLimit):
    dynamicChecksumList = []
    for i in range(0, 10):
        dynamicChecksumList.append(i)
    for i in range(10, upperLimit+1):
        length = getIntegerPlaces(i)
        size = 10**(length-1)
        firstNumber = i // size
        ancestor = i-(firstNumber*size)
        newChecksum = firstNumber + dynamicChecksumList[ancestor]
        dynamicChecksumList.append(newChecksum)
    return dynamicChecksumList
首先,我创建一个空列表,然后用它们各自的平凡和填充数字0-9。 然后我看9以上的所有数字,直到上限。了解他们的长度。然后我继续找出数字的第一位数字。然后,我计算没有前导数字的数字。例如:如果我的i是5432,我将得到432。因为我已经保存了432的交叉和,所以我可以把交叉和加到我的前导位上,基本上就完成了

def getIntegerPlaces(theNumber):
    if theNumber <= 999999999999997:
        return int(math.log10(theNumber)) + 1
    else:
        counter = 15
        while theNumber >= 10**counter:
            counter += 1
        return counter
def getIntegerPlaces(编号):
如果编号=10**计数器:
计数器+=1
返回计数器
第二个函数是我在这里发现的,关于如何计算给定数字的位数的问题

这里有没有办法(我想会有)加快速度? 此外,还请提供如何节省内存的提示。只是为了好玩,我试着把n设为10亿。我的内存(16GB)有点爆炸了;)

有两个主要区别:

  • bytearray
    对每个计算值使用一个字节,这节省了大量内存。它只允许255位以下的数字,但对于小于26位的数字就足够了
  • 最后一个数字的剥皮比第一个数字的剥皮容易得多

这在python中应该尽可能快。打印结果时要小心,因为它可能比计算本身花费更多的时间(尤其是在内存中复制时)。

交叉和是什么?
def digitSums2(n):
    n = (n + 9) // 10 * 10 # round up to a multiple of 10
    result = bytearray(range(10))
    for decade in range(1, n//10):
        r_decade = result[decade]
        for digit in range(10):
            result.append(r_decade + digit)
    return result