Check for duplicates in a randomly generated list and replace them
<p>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.</p>

<pre><code>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)
</code></pre>

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

<pre><code>GRID_TILES * GRIDTILES / 5
</code></pre>

<p>Searching each time through your whole BOMBS list would cost you <code>O(n)</code> (linear time). Why don't you use a <a href="https://docs.python.org/2/library/sets.html" rel="nofollow">set</a> instead? a Set guarantees that you ll end up with distinct (in terms of hashing) elements.</p>

<pre><code>from random import randint

def create_bombpos():
BOMBS = set()
i = 0
while i&lt;NUM_BOMBS:
   x = randint(1, GRID_TILES)
   y = randint(1, GRID_TILES)
   if (x,y) not in BOMBS
       BOMBS.add((x, y))
       i = i + 1
print(BOMBS)
</code></pre>

<p>Let me give u an example of a set:</p>

<pre><code>&gt;&gt;&gt; a = set()
&gt;&gt;&gt; a.add((1,2))
&gt;&gt;&gt; a
{(1, 2)}
&gt;&gt;&gt; a.add((1,2))
&gt;&gt;&gt; a.add((1,3))
&gt;&gt;&gt; a.add((1,2))
&gt;&gt;&gt; a
{(1, 2), (1, 3)}
</code></pre>

<p>I can add the same element to a set many times, but only 1 instance will be present.</p>

python python-3.x random