Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need an incrementor / iterable as a variable in another generator fn

Two attempts failed.

Method 1

Desired Output
coords are (20, 0, 0)
coords are (40, 0, 0)
coords are (60, 0, 0)
coords are (80, 0, 0)

Actual output
coords are (1, 0, 0)
coords are (20, 0, 0)
coords are (2, 0, 0)
coords are (60, 0, 0)

yDims = 10
Gap = 10
HowManyParts = 10

def Coords():
    global yDims
    global HowManyParts
    count = 0
    value = 0
    for i in range(HowManyParts):
        count +=1
        value += (yDims + Gap) * count
        yield count
        yield value 
C1 = Coords()
iterC1 = iter(C1)

testfn = lambda :(f"coords are ({next(iterC1)}, 0, 0)")

for i in range(4):
    print(testfn())

Method 2: using a separate generator as a variable, directly in the fn, or using a reference to it outside the fn = this error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

value += (yDims + Gap) * {next(arrCount)}

value += (yDims + Gap) * a


TypeError: unsupported operand type(s) for *: 'int' and 'set'

What’s a correct way to do this? What’s the lesson here?

>Solution :

Just using next, you don’t want to yield count as this isn’t one of your coordinates, also with using += you shouldn’t increase count at each iteration.

yDims = 10
Gap = 10
HowManyParts = 10

def Coords():
    count = 1
    value = 0
    for i in range(HowManyParts):
        value += (yDims + Gap) * count
        yield value 
C1 = Coords()
iterC1 = iter(C1)

testfn = lambda :(f"coords are ({next(iterC1)}, 0, 0)")

for i in range(4):
    print(testfn())

Output:

coords are (20, 0, 0)
coords are (40, 0, 0)
coords are (60, 0, 0)
coords are (80, 0, 0)

Or if you need count for something else, you can do this using itertools (What's the best way of skip N values of the iteration variable in Python?):

import itertools

yDims = 10
Gap = 10
HowManyParts = 10

def consume(it, n):
    return next(itertools.islice(it, n-1, n), None)

def Coords():
    count = 0
    value = 0
    for i in range(HowManyParts):
        count += 1
        value = (yDims + Gap) * count
        yield count
        yield value

C1 = Coords()
iterC1 = iter(C1)

testfn = lambda :(f"coords are ({consume(iterC1, 2)}, 0, 0)")

for i in range(4):
    print(testfn())

Output

coords are (20, 0, 0)
coords are (40, 0, 0)
coords are (60, 0, 0)
coords are (80, 0, 0)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading