How do I loop through a list in Python to make sure there are no repeats?

In my code I am trying to generate coordinates for battleship without having any repeat coordinates. I only manage far more coordinates than I asked for or none at all. What am I doing wrong in my loop/how can I fix this?

from random import randint

board = []  #Create an empty array to act as the game board.
ships = []  #Create an empty array to hold the locations of the random ships.

board_size = int(input("Enter your desired board size: "))          #Ask the user for their preferred board size.
ship_number = int(input("Enter the number of ships you want to find: "))    #Ask the user for their preferred ship number.

ships_found = 0 #Set the counter of the number of user-found ships to start at 0.

def generate_board(board_size):         #Define a function to generate the initial board.
    for each_item in range(board_size):     #For each item in the range of the board's size,
        board.append(["O"] * board_size)    #Append an O to the board as many time as the user's board size says.
generate_board(board_size)

def print_board(board):         #Define a function to print the current board.
    for row in board:           #For each row in the board,
        print(" ".join(row))    #Print each chacter, separated by a space.

def generate_ships(ship_number,board):
    for each_ship in range(ship_number):
        new_ship = [randint(0, len(board) - 1),randint(0, len(board) - 1)]
        for each_item in ships:
            if each_item == new_ship:
                ships.pop()
                ships.append(new_ship)
            else:
                ships.append(new_ship)

generate_ships(ship_number,board)

Answers


While using set() to remove duplicates would technically answer the question in your title, I'd recommend rethinking your approach (and rewriting generate_ships, the logic for which looks like it might not be doing what you want it to).

Rather than randomly generating a coordinate, you could select a random element from the set of available coordinates (your board coordinates after removing the coordinates where there are already ships). This way you only ever select the number of ships you ask for and you don't have to worry about checking for duplicates.


Need Your Help

How to create a message box with tkinter?

python tkinter messagebox

I've been trying to build a fairly simple message box in tkinter that has "YES" and "NO" buttons. When I push the "YES" button internally it must go and write YES to a file. Similarly, when "NO" is

Emacs region highlighting

emacs elisp

Is there a way to highlight a string in a text (but not ALL such strings) in a buffer where font-lock-mode is on.