Python-函数(生成器),其值是序列列表 - 初学者

时间:2021-05-26 16:01:10

I must create a function(generator) f(n), which will return all of sequence(list) where the difference between within word is greater than 1. For example,if we use:

我必须创建一个函数(生成器)f(n),它将返回所有序列(列表),其中单词内的差异大于1.例如,如果我们使用:

for i in f(5):
     print(i)

The output is:

输出是:

[1]
[2]
[3]
[4]
[5]
[1,3]
[2,4]
[3,5]
[1,4]
[2,5]
[1,5]
[1,3,5]

How can I do that?

我怎样才能做到这一点?

def f(n):
  for i in range(1,n+1,2):
    yield i
for i in f(5):
    print(i)

1 个解决方案

#1


If I understand correctly, you can achieve this with recursion:

如果我理解正确,你可以通过递归实现这一点:

def f(n):
    return f_2(n, 2)
def f_2(n, index):
    if n is index:
        for i in range(1,n+1,1):
            yield [i]
        return
    for start in range(1, n-index+1):
        l=[]
        for j in range(start,n+1,index):
            l.append(j)
            if len(l) > 1:
                yield l
    for value in f_2(n, index+1):
        yield value
for i in f(5):
    print(i)

produces:

[1, 3]
[1, 3, 5]
[2, 4]
[3, 5]
[1, 4]
[2, 5]
[1, 5]
[1]
[2]
[3]
[4]
[5]

#1


If I understand correctly, you can achieve this with recursion:

如果我理解正确,你可以通过递归实现这一点:

def f(n):
    return f_2(n, 2)
def f_2(n, index):
    if n is index:
        for i in range(1,n+1,1):
            yield [i]
        return
    for start in range(1, n-index+1):
        l=[]
        for j in range(start,n+1,index):
            l.append(j)
            if len(l) > 1:
                yield l
    for value in f_2(n, index+1):
        yield value
for i in f(5):
    print(i)

produces:

[1, 3]
[1, 3, 5]
[2, 4]
[3, 5]
[1, 4]
[2, 5]
[1, 5]
[1]
[2]
[3]
[4]
[5]