【发布时间】: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], [2], [3, 4], [5, 6]]
- 第一个结果 = [[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], [2], [3], [4], [5, 6]]
- 第三个结果 = [[1], [2], [3], [4], [5], [6]]
【问题讨论】:
标签: python python-2.7 iterator generator