【问题标题】:Recursively find adjacent coordinates for n-dimensional array递归查找n维数组的相邻坐标
【发布时间】:2020-06-23 21:43:39
【问题描述】:

对于给定的任何坐标元组(例如 (2,2) 或 (1,2,3) 或 (4,5,6,7,8) 等),我如何获取列表所有相邻坐标。
那么,

find_adjacents((2,2))    

  >>[[1,1],[1,2],[1,3],[2,1],[2,3],[3,1],[3,2],[3,3]]  

find_adjacents((2,2,2,2))

would return something with 3^4-1 elements

您可以忽略这种情况的边缘情况(想象索引范围从 -inf 到 inf)

【问题讨论】:

  • “所有相邻坐标”是模糊的;你到底什么意思?为什么这是预期的输出?为什么要递归地做呢?
  • 对不起。我的意思是任何元素都在每个指定坐标元素的 1 以内(包括“角”)。 (1,1,1) 的角相邻元素将是 000,200,002,020,220,022,202,222。
  • 我明白了——但不包括输入本身?
  • 是的。所以它总是 3^4-1 个元素而不是 3^4

标签: python list recursion tuples


【解决方案1】:

您可以为此使用itertools.product。范围的笛卡尔积将包括输入本身,因此我们需要在之后将其删除。 list.pop 适用于此,因为产品是按顺序生成的,因此输入本身将始终恰好是中间元素。

from itertools import product

def neighbours(t):
    ranges = [(x-1, x, x+1) for x in t]
    result = list(product(*ranges))
    result.pop(len(result) // 2)
    return result

示例(为便于阅读而格式化):

>>> neighbours( (1, 2) )
[(0, 1), (0, 2), (0, 3),
 (1, 1),         (1, 3),
 (2, 1), (2, 2), (2, 3)]

>>> neighbours( (1, 1, 1) )
[(0, 0, 0), (0, 0, 1), (0, 0, 2),
 (0, 1, 0), (0, 1, 1), (0, 1, 2),
 (0, 2, 0), (0, 2, 1), (0, 2, 2),

 (1, 0, 0), (1, 0, 1), (1, 0, 2),
 (1, 1, 0),            (1, 1, 2),
 (1, 2, 0), (1, 2, 1), (1, 2, 2),

 (2, 0, 0), (2, 0, 1), (2, 0, 2),
 (2, 1, 0), (2, 1, 1), (2, 1, 2),
 (2, 2, 0), (2, 2, 1), (2, 2, 2)]

【讨论】:

    【解决方案2】:

    你可以使用递归:

    def combos(d, c = []):
      if not d:
         yield c
      else:
         yield from [i for b in range(d[0]-1, d[0]+2) for i in combos(d[1:], c+[b])]
    
    vals = (2,2)
    print(list(combos(vals)))
    print(list(combos((1, 1, 1))))
    

    输出:

    [[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]
    [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [0, 1, 2], [0, 2, 0], [0, 2, 1], [0, 2, 2], [1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 1, 0], [1, 1, 1], [1, 1, 2], [1, 2, 0], [1, 2, 1], [1, 2, 2], [2, 0, 0], [2, 0, 1], [2, 0, 2], [2, 1, 0], [2, 1, 1], [2, 1, 2], [2, 2, 0], [2, 2, 1], [2, 2, 2]]
    

    【讨论】:

      猜你喜欢
      • 2018-06-27
      • 2019-02-01
      • 2013-09-13
      • 2021-05-22
      • 2017-12-23
      • 2017-10-04
      • 2010-12-17
      • 2021-08-26
      • 2017-12-18
      相关资源
      最近更新 更多