L. de Boer L. de Boer - 2 months ago 6
Python Question

Check for duplicates in a randomly generated list and replace them

I am making a minesweeper game with randomly generated bombs. Yet at times I have found that there are duplicates in my list of coordinates of bombs. How do I check for duplicates in a list and replace them with other randomised coordinates.

from random import randint

def create_bombpos():
global BOMBS, NUM_BOMBS, GRID_TILES
for i in range(0, NUM_BOMBS):
x = randint(1, GRID_TILES)
y = randint(1, GRID_TILES)
BOMBS.append((x, y))
print(BOMBS)


The user can decide how big the board is by input of
GRID_TILES
.
If they input 5, the board will be 5x5. The ammount of bombs is:

GRID_TILES * GRIDTILES / 5

Answer
from random import randint

def create_bombpos():
    global BOMBS, NUM_BOMBS, GRID_TILES
    i = 0
    while i<NUM_BOMBS:
       x = randint(1, GRID_TILES)
       y = randint(1, GRID_TILES)
       if (x,y) not in BOMBS
           BOMBS.append((x, y))
           i = i + 1
    print(BOMBS)

If the newly generated point is already in the list, then i won't get incremented, and we will find another newly generated point, till it is not present in BOMBS.

Hope it helps!!