我们有一个大的数字,例如(10 ** 1500000)+1,并且想要将其转换为基数3。 以下是使用我们在普通Python中发现的最快方法(不使用numpy或CAS库)运行代码。
如何加速基本转换(至基本3)的性能?
我们想知道如何通过以下两种方式做到这一点:
非常欢迎任何帮助。这是我们当前的代码:
#### --- Convert a huge integer to base 3 --- ####
# Convert decimal number n to a sequence of list elements
# with integer values in the range 0 to base-1.
# With divmod, it's ca. 1/3 faster than using n%b and then n//=b.
def numberToBase(n, b):
digits = []
while n:
n, rem = divmod(n, b)
digits.append(rem)
return digits[::-1]
# Step 2: Convert given integer to another base
# With convsteps == 3, it's about 50-100 times faster than
# with with convsteps == 1, where numberToBase() is called only once.
def step2(n, b, convsteps):
nList = []
if convsteps == 3: # Here the conversion is done in 3 steps
expos = 10000, 300
base_a = b ** expos[0]
base_b = b ** expos[1]
nList1 = numberToBase(n, base_a) # time killer in this part
nList2 = [numberToBase(ll, base_b) for ll in nList1]
nList3 = [numberToBase(mm, b) for ll in nList2 for mm in ll]
nList = [mm for ll in nList3 for mm in ll]
else: # Do conversion in one bulk
nList = numberToBase(n, b) # that's the time killer in this part
return nList
if __name__ == '__main__':
int_value = (10**1500000)+1 # sample huge numbers
# expected begin: [2, 2, 0, 1, 1, 1, 1, 0, 2, 0]
# expected time: 4 min with convsteps=3
base = 3
# Convert int_value to list of numbers of given base
# -- two variants of step2() using different convsteps params
numList = step2(int_value, base, convsteps=1)
print(' 3-1: numList begin:', numList[:10])
# A value of '3' for the parameter "convsteps" makes
# step2() much faster than a value of '1'
numList = step2(int_value, base, convsteps=3)
print(' 3-3: numList begin:', numList[:10])
在How to calculate as quick as possible the base 3 value of an integer which is given as a huge sequence of decimal digits (more than one million)?中 在进行基本转换之前,还有一个类似的问题,需要更多步骤。在此问题中,我们将重点放在那部分上,该部分到目前为止大部分时间都在消耗,而对于这一点我们还没有得到答案。
在Convert a base 10 number to a base 3 number中,巨大数字的性能方面也未得到处理。
答案 0 :(得分:6)
这是一种方法,该方法通过每次调用的基数平方递归来扩展您的onEvent: function(dt)
{
$.each(dt.lst, function(ind, ele)
{
var htm = '<option value="' + ele + '">' + ele + '</option>';
$('#myMultiSelectId').append(htm);
});
$('#myMultiSelectId').multiselect({
maxHeight: 300,
includeResetOption: true,
resetText: 'Deselect All'
});
$('#myMultiSelectId').multiselect('rebuild');
}
解决方案。需要一些额外的工作才能删除前导零。
convsteps
我的快速计时测试表明,它与您的def number_to_base(n, b):
if n < b:
return [n]
else:
digits = [d for x in number_to_base(n, b*b) for d in divmod(x, b)]
return digits if digits[0] else digits[1:]
在误差范围内相同。但这更简单,并且可能有更少的错误。