1

Before posting, I have done following reading:

But I couldn't get my code working.

here is the code:


import string

arr = [0, 1, 2, 3, 4]
required = 4

red = ['0']
alpha = string.printable[10:62]
ss = ''
it = len(arr) - required + 1
for i in range(required):
    now = alpha[i]
    rd = '-'.join(red)
    ss += '\t' * (i + 1) + f'for {now} in range({it}-{rd}):\n'
    red.append(now)

exec('def inner_reducer():\n' + ss + '\t' * (required + 1) + f'yield {red[-1]}')


a = inner_reducer()
print(a.__next__())
print(a.__next__())
print(a.__next__())
print(a.__next__())

instead of writing directly in global scope, I need a generator that takes arr and required as parameter, after assigning to the generator, call __next__() to generate value.

Any help is appreciable.

Weilory
  • 2,621
  • 19
  • 35

1 Answers1

1

@JordanBrière The code 100% works, but I need to write it into a generator, which takes an array and a number as parameter, and yields values. so I can import this function

You could use a factory function. E.g.

import string

def make_inner_reducer_function(arr, required):
    red = ['0']
    alpha = string.printable[10:62]
    ss = ''
    it = len(arr) - required + 1
    for i in range(required):
        now = alpha[i]
        rd = '-'.join(red)
        ss += '\t' * (i + 1) + f'for {now} in range({it}-{rd}):\n'
        red.append(now)

    exec('def inner_reducer():\n' + ss + '\t' * (required + 1) + f'yield {red[-1]}')

    return locals()['inner_reducer']

f = make_inner_reducer_function([0, 1, 2, 3, 4], 4)

a = f()
print(a.__next__())
print(a.__next__())
print(a.__next__())
print(a.__next__())
Jordan Brière
  • 1,045
  • 6
  • 8