0

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:

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?

1 Answers1

0

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. The use of global is unnecessary here. When do I need to use the global keyword in python

yDims = 10
Gap = 10
HowManyParts = 10

def Coords():
    value = 0
    for i in range(HowManyParts):
        value += (yDims + Gap)
        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)
Nin17
  • 2,821
  • 2
  • 4
  • 14
  • So the first answer only works by doubling the answer, it's not invariant to changing variables, but thanks for the other options : ) – Richard Ainsworth Apr 18 '22 at 06:06
  • I'm not sure what you mean? It works if you change yDims, gap and HowManyParts. It works by adding yDims + gap to the previous answer – Nin17 Apr 18 '22 at 06:12