-1

I've read numerous posts on this, and I realise lots of people have asked this, but I can't understand what I'm doing wrong. I'm trying to draw a grid with coordinates for a project I'm working on, and I was trying some code for generating it. I tryed this one, but I keep getting that error. What's wrong with the code? I've tryed different indentations but it doesn't work.

stepsize = 0.001

for x in range(0, 10, stepsize):
  for y in range(0, 10, stepsize):
    yield (x,y)

How can I generate a regular geographic grid using python?

^^The original q+a

Thanks to everyone who helped, I'm not sure why that code was posted considering it wouldn't work anyway! Sorry for my misunderstanding, I haven't used generators before. :)

2 Answers2

2

The yield keyword is used to "return" a generator object from a function

Stack Overflow Question on the yield keyword

It cannot be used outside a function, like in your code.

If this was under a def statement, then it would be fine, however there is no def statement here, so it raises an error


Also, not in relation to the question, but these lines won't work:

for x in range(0, 10, stepsize):
  for y in range(0, 10, stepsize):

because stepsize is a float, and the range function only handles integers - it will say something like TypeError: 'float' object cannot be interpreted as an integer

The Thonnu
  • 3,578
  • 2
  • 8
  • 30
0

To add to what was already said, you could implement your code by composing generators to produce the required output.

def increment(start, end, delta):
    while start < end:
        yield start
        start += delta

def double_increment(start, end, delta):
    for x in increment(start, end, delta):
        for y in increment(start, end, delta):
            yield x, y

Example:

for x, y in double_increment(0, 1, 0.4):
    print(f"{x:.2f} {y:.2f}")
0.00 0.00
0.00 0.40
0.00 0.80
0.40 0.00
0.40 0.40
0.40 0.80
0.80 0.00
0.80 0.40
0.80 0.80

You could also use product to produce the double increment:

from itertools import product
for x, y in product(increment(0, 1, 0.4), repeat=2):
    print(f"{x:.2f} {y:.2f}")

Combining more itertools you could do:

from itertools import product, count, takewhile
for x, y in product(takewhile(lambda x: x < 1, count(0, step=0.4)), repeat=2):
    print(f"{x:.2f} {y:.2f}")
flakes
  • 21,558
  • 8
  • 41
  • 88