I experience something strange from my point of view
I need to generate alternatively True
and False
values like this:
False, True, False, False, True, True, False, False, False, True, True, True, False, False, False, False, True, True, True, True, ...
I need to get one False
, one True
, then two False
, two True
, then three False
, three True
, etc
In my mind, using the yield
keyword in a function was a good way to achive this:
def generateFalseTrueRangesAlternatively(limit):
limitForChange = 0
index = 0
rv = True
for i in range(0, limit):
if index == limitForChange:
rv = not rv
index = 0
if not rv:
limitForChange += 1
index += 1
yield rv
for i in range(0,4):
g = generateFalseTrueRangesAlternatively(20)
print(next(g))
But I get only False
values:
False
False
False
False
As a workaround, I wrote the following code, which generates a list :
def generateFalseTrueRangesAlternativelyList(limit):
limitForChange = 1
index = 0
rv = False
out = []
for i in range(0, limit):
if index == limitForChange:
rv = not rv
index = 0
if not rv:
limitForChange += 1
index += 1
out.append(rv)
return out
l = generateFalseTrueRangesAlternativelyInList(6)
for i in range (0,6):
print(l[i])
Which outputs:
False
True
False
False
True
True
Questions
What is wrong with my generateFalseTrueRangesAlternatively
function ?
How could it be modified to behave like the generateFalseTrueRangesAlternativelyInList
but without creating a list ?
Is there something I did not understand with yield
usage and what ?
Actually, my curiosity needs to be satisfied by answering this fundamental question: why ?
(My Python version: 3.5.4)