【问题标题】:Create repeated loop to generate neighbours创建重复循环以生成邻居
【发布时间】:2016-10-31 02:34:32
【问题描述】:

我正在尝试生成具有以下条件的 nieghbours 子列表:

  • 输入可能是列表 S = [1,2,3,4,5,6] 的分区

使用拆分操作的邻域标准

  • 条件 1 - 拆分列表中的最大元素。
  • 标准 2 – 总是将最大的元素除以 //2 (例如,对于具有 3 个成员的元素,将分为 1 个元素和另一个元素)
  • 标准 3 - 继续拆分,直到无法再拆分。

我一直在编写用于生成结果的迭代函数。

这是我目前所拥有的:

# initialize
neighlists = []
beginning = []
ending = []
newstart = []

inputlist = [[1], [2], [3, 4], [5, 6]]

# find the biggest element of the list
def find_biggest(inputlist):
    biggest = max(inputlist, key=len)
    return biggest

biggest = find_biggest(inputlist)
print 'The largest element in the list is: ', biggest

# Function to process biggest component
def process_biggest(biggest):
    split_half = len(biggest)//2
    part_one = [biggest[:split_half]] + [biggest[split_half:]]
    yield part_one

for elem in process_biggest(biggest):
    beginning = elem

# Function to process the rest
def process_therest(inputlist):
    therest = []
    for elem in inputlist:
        if len(elem) < len(biggest) or elem is not biggest:
            therest.append(elem)
    yield therest

for elem in process_therest(inputlist):
    ending = elem

# Function to construct new neighbour
def construct_neighbour(beginning,ending):
    new_neigh = beginning + ending
    yield new_neigh

for neighbour in construct_neighbour(beginning,ending):
    # store the values in the neighlist table
    neighlists.append(sorted(neighbour))

    # use the neighbour as new inputlist
    inputlist = neighbour
  1. 第一个例子:

    • 初始输入 = [[1], [2], [3, 4], [5, 6]]
    • 第一个结果 = [[1], [2], [3], [4], [5, 6]]
    • 第二个结果 = [[1], [2], [3], [4], [5], [6]]
  2. 第二个例子:

    • 初始输入 = [[1], [2, 3, 4], [5, 6]]
    • 第一个结果 = [[1], [2], [3, 4], [5, 6]]
    • 第二个结果 = [[1], [2], [3], [4], [5, 6]]
    • 第三个结果 = [[1], [2], [3], [4], [5], [6]]

【问题讨论】:

    标签: python python-2.7 iterator generator


    【解决方案1】:

    类似这样的:

    input = [[1], [2, 3, 4], [5, 6]]
    
    def splitList(input):
        length = len(input)
        split = length/2
        left = input[:split]
        right = input[split:]
        return [left, right]
    
    def splitNeighbors(input):
        lengths = map(len, input)
        longest = max(lengths)
        if longest > 1:
            index = lengths.index(longest)
            split = splitList(input[index])
            output = input[:index] + split + input[index+1:]
            return splitNeighbors(output)
        return input
    
    output = splitNeighbors(input)
    print(output)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      • 2018-12-01
      • 2020-05-14
      • 2011-11-24
      • 2018-07-20
      相关资源
      最近更新 更多