-1

I want to design a generator as gen(num):

the idea is to generator a sequence of number. such as if num=3, the sequence will be (1,2,3,2,1,2,3,2,1.....). if num=4, the sequence will be (1,2,3,4,3,2,1,2,3,4,3,2,1,....)

def gen(num)

And how to use this generator in a for loop?

such as

a = [1,2,3,4,5]
b = gen(10)
for item in a:
    a+next(b)

it is good to use next(b) or we have better solution?

jason
  • 1,998
  • 3
  • 22
  • 42
  • is the sequence following a certain pattern? Also, what would be the max length of the sequence? – Agawane Jun 19 '19 at 21:20

1 Answers1

1
def gen(n):
    c, i = 1, -1
    while True:
        if c in (1, n):
            i *= -1
        yield c
        c += i

a = [1,2,3,4,5,6,7,8,9,10]
b = gen(3)
for va, vb in zip(a, b):
    print('{}\t{}\t{}'.format(va, vb, va + vb))

Prints:

1   1   2
2   2   4
3   3   6
4   2   6
5   1   6
6   2   8
7   3   10
8   2   10
9   1   10
10  2   12

Update: Version of the generator with itertools.cycle:

from itertools import cycle

gen = lambda n: cycle([*range(1, n+1)] + [*range(n-1, 1, -1)])
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91