Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

python - How to continuously generate 2D-Lists until a certain specification is met

I've written the following Python Program:

This program generates a 30x30 2D List and places 10 marks randomly around the grid. I want to modify this program to continuously generate this 30x30 2D whilst placing marks and to stop only when each mark is a set amount of spaces apart (ex minimum 5 meters apart). I know I'd have to use the Pythagorean theorem to do this but not sure how to implement it into my code.

import random
listSize = 30
marks = 10
grid = []
for i in range(listSize): 
    grid.append([0] * listSize)
for i in range(marks):
    x = random.randint(0, listSize - 1)
    y = random.randint(0, listSize - 1)
    grid[x][y] = 1 
for row in grid:
    print(row)
question from:https://stackoverflow.com/questions/65600731/how-to-continuously-generate-2d-lists-until-a-certain-specification-is-met

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Rather than storing marks in the grid, you should create an addition list which stores the x,y positions of each mark, then loop over that to check if each pair satisfies the condition. So something like this:

import math

points = [(0,0), (5,10), (100,200)]
for n, point_n in enumerate(points):
    for point_m in points[n+1:]:
        if math.dist(point_n, point_m) < 5:
            print('distance less than 5!')

Note math.dist is only available in Python3.8 and higher, you will have to code the distance function yourself in lower versions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...