I have the following problem in which I want to generate patterns with a 0 introduced. The problem is that this should be space efficient, and thus I would like to use a generator that creates and returns one of the patterns at a time (i.e. I do not want to create a list and return it.) I am at a loss here because I don't know what I am doing wrong in calling the generator, so any help would be appreciated!
original pattern = [ 0. 1. 1. 2.] generator should generate and return these: [ 0. 0. 1. 2.], [0. 1. 0. 2.], [ 0. 1. 1. 0.]
However I can just yield one of the patterns with a call to the generator (the additional 1.0 is not an issue just to not cause any confusion...) and not all of them in succession.
yielded subpattern = (array([ 0., 1., 0., 2.]), 1.0)
The following is my code:
import numpy as np
def removeoneletter(subpattern):
# generator = []
originalpattern = subpattern
subpatterncopy = subpattern.copy()
nonzero = np.nonzero(subpattern)
listnonzero = nonzero[0].tolist()
# only replace elements at nonzero positions with zero
for i in listnonzero:
subpatterncopy = subpattern.copy()
position = i
transaction = subpatterncopy[i]
np.put(subpatterncopy, position, 0)
print('subpattern generator')
print(subpatterncopy)
# generator.append((subpatterncopy, transaction))
yield((subpatterncopy, transaction))
if i == len(listnonzero):
break
and the function gets called by another function like so:
def someotherfunction():
combinations = removeoneletter(subpatterncopy)
for x in combinations:
# x = next(combinations)
print('yielded subpattern')
print(x)