创建重复循环以生成邻居

时间:2016-06-28 16:36:21

标签: python python-2.7 iterator generator

我试图使用以下标准生成nieghbours子列表:

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

使用拆分操作的邻居标准

  • 条件1 - 分割列表中最大的元素。
  • 标准2 - 始终将最大元素分割为// 2 (例如,对于具有3个成员的元素将分为1个,其中一个元素,另一个元素分成2个)
  • 标准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]]

1 个答案:

答案 0 :(得分:0)

这样的事情:

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)