简体   繁体   中英

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM