【发布时间】:2017-05-16 10:15:34
【问题描述】:
我正在尝试编写一种高效的算法,可以找到数组所有可能的连续子字符串的总和(保留顺序和组合可以是任意长度)
例如:
[1,2,3,4] -> 1 + 2 + 3 + 4 + 12 + 23 + 34 + 123 + 234 + 1234 = 1670
同样重要的是要注意数组可以重复多次
到目前为止我最好的尝试可能是这样的:(n 是一组数字)
k = 3 // number of times the array repeats
length = len(n)
total = 0
for i in range(0, length*k):
for exp in range(0, length*k-i):
//iterate though all of the possible powers of ten a certain number could be in
// ie. all the different places that number could be in for all combinations
total += ((n[i % length] * 10**exp) * (i + 1))
// ^ turns number from standard from into int. The i + 1 account for
// the fact the number could be in the same position in more than one combination
return total
但是,该算法必须针对其中包含超过 10^20 个数字的数组运行,因此我正在寻找一种更快的算法。
注意所有数字都是个位数,数字可以重复
【问题讨论】:
-
您尝试过 itertools.combinations 吗?
-
@PetarPetrovic 我考虑过,但数组太大而无法使用整个东西 - 我收到内存错误。它重复多次,所以我只使用未重复的部分
-
@PetarPetrovic Ive 更新了我的代码以反映这一点
-
10^20 个数字?你从哪里得到一台内存超过 100 EB 的计算机?
-
您的示例没有显示“组合”,它显示了子字符串。
标签: algorithm math numbers mathematical-optimization discrete-mathematics