Reputation: 1
Working on a basic project to simulate the life cycle of an organism using matplotlib. The organism's position is defined by list [x,y], and its position is randomly generated. Organism being the class
for i in range(numorganisms):
posX = random.randint(0,XMAX)
posY = random.randint(0,YMAX)
creatures.append(organism([posX,posY]))
There may be about 100 of these in the plot, meaning collisions will occur. I want to be able to search the list of creatures for instances where posX and posY are both equal, and then create a new list of those positions.
Upvotes: 0
Views: 39
Reputation: 2492
This assumes you have some way to get the positions out of the instance of organism
.
###############################
# This just recreates what I think you already have
import random
class organism:
def __init__(self, l):
self.l = l
XMAX = YMAX = 100
creatures = []
for i in range(100):
posX = random.randint(0,XMAX)
posY = random.randint(0,YMAX)
creatures.append(organism([posX,posY]))
print(creatures)
###############################
# Determine if there are redundancies
positions = [x.l for x in creatures]
print(positions)
collisions = [i for i in positions if positions.count(i) > 1]
print(collisions)
Upvotes: 0
Reputation: 23498
You may easily do this:
existing = set()
for i in range(numorganisms):
posX = random.randint(0,XMAX)
posY = random.randint(0,YMAX)
if (posX, posY) not in existing :
creatures.append(organism([posX,posY]))
existing.add( (posX, posY) )
else :
pass # do something else
Upvotes: 2