python - 菜鸟算法设计

标签 python algorithm logic

<分区>

我是算法设计的新手。我有一个大约 8128 个整数的列表。我需要创建一个算法来创建 128 种不同的唯一数字组合。

第一个数字 1 没有被任何组合使用。前 6 个数字序列开始如下:

  1. 2,4,7,11,16,22
  2. 3,6,10,15,21
  3. 5,9,14,20
  4. 8,13,19
  5. 12,18
  6. 17

我注意到数字之间的间隔在每个序列之间增加 1。我还看到它似乎选择了第一个唯一的(未使用的)整数来开始一个序列。我一直在尝试用 Python 实现它。

我想解决设施位置问题。我有 8128 个距离值存储在一个数组中。下面的代码片段使前两个相对距离数组正确,但第三个重复了之前已经使用过的值

distances = [[0 for col in range(2)] for row in range(128)] #this array contains line numbers that contain distances

#1st iteration works
startpoint = 0
count = 1
diff = 2

while startpoint < 8127:
    print distance[startpoint+diff]
    startpoint = startpoint+count
    count += 1
    diff += 2

#2nd iteration works
startpoint = 1
count = 2
diff = 3

while startpoint < 8127:
    print distance[startpoint+diff]
    startpoint = startpoint+count
    count += 1
    diff += 2

#3rd iteration repeats a value
startpoint = 2
count = 3
diff = 4

while startpoint < 8127:
    print distance[startpoint+diff]
    startpoint = startpoint+count
    count += 1
    diff += 2

是否有该算法的示例或实现?

最佳答案

用函数表示距离可能比用数组表示更好:

D(I, J) = I + J

其中 IJ 是(非 Python 的)基于 one 的索引。 (你意识到在你的代码中,距离都是零吗?)

此外,您可能应该考虑行数 (128),而不是值的总数 (8128)。我不清楚你的三个迭代的目的。你不应该对行和列进行循环吗?

无论如何:

N = 128
n = 2

for i in range(N):
    m = n
    s = []
    for j in range(N - i):
        s.append(m)
        m += (j + 1) + (i + 1)

    print i + 1, s        
    n += i + 1

您可以用另一种方式解决这个问题,注意每个数字只出现一次并遵循一种模式:

 2   4   7  11
    /   /   /
   /   /   /
  /   /   /
 3   6  10
    /   /
   /   /
  /   /
 5   9
    / 
   / 
  / 
 8

然后您可以预先创建所有列表并在第二个循环中打印它们:

n = 2
L = []

for i in range(N):
    L.append([])

    for LL in reversed(L):
        LL.append(n)
        n += 1

for i, LL in enumerate(L):
    print i + 1, LL

关于python - 菜鸟算法设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22681432/

相关文章:

python - 在python中导入36列进行绘图,第一列是日期

PHP 登录脚本不工作

c++ - 如何在没有 float / double 的情况下生成均匀分布和高斯分布的伪随机数?

c - 我的函数的时间复杂度是多少?

algorithm - 如何测试时间复杂度 "experimentally"?

c++ - 请给我一个 boost-multi-index stub - 带有 std::cout

r - 为每个患者寻找最接近的匹配时间

python - 如何获取 GeoDataFrame 中多边形内的所有点?

Python:将输出保存到 csv 文件时出错?

Python Pandas - Fillna(method=ffill) 导致 NameError