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?
>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)