如何随机化切片?

2024-05-16 15:55:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使战列舰,我在一个列表中的船舶“董事会”和船舶的长度将由切片决定。我试图用随机选择移动飞船,但我很快意识到随机选择一次只移动一个元素,但是飞船有2-5个元素。我想看看是否可以将列表中的切片随机化为切片上指定的单位。random.shuffle似乎不起作用

import random

board = "o"

board = [board] * 49

ship_two_space = board[0:2]

ship_three_space = board[0:3]

ship_three_space_second = board[0:3]

ship_four_space = board[0:4]

ship_five_space = board[0:5]

Tags: board元素列表单位切片spacerandom船舶
1条回答
网友
1楼 · 发布于 2024-05-16 15:55:28

装运位置不能重叠-使用集合记录占用的空间

occupied = set()

定义规格

N = 49
board = ['o'] * N
ship_specs = [('two_space', 2), ('three_space1', 3), ('three_space2', 3),
              ('four_space', 4), ('five_space', 5)]

开始制作船只-使用collections.namedtuple来定义船只

Ship = collections.namedtuple('Ship', ('name','indices', 'slice'))

def get_position(length):
    '''Determine the unique position indices of a ship'''

    start = random.randint(0, N-length)
    indices = range(start, start + length)
    if not occupied.intersection(indices):
        occupied.update(indices)
        return indices, slice(start, start + length)
    else:
        return get_position(length)

ships = []

for name, length in ship_specs:
    indices, _slice = get_position(length)
    ships.append(Ship(name, indices, _slice))


print(board)
for ship in ships:
    board[ship.slice] = str(len(ship.indices))*len(ship.indices)
print(board)
print([(ship.name, ship.slice) for ship in ships])

>>> 
['o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o']
['o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', '2', '2', '4', '4', '4', '4', '3', '3', '3', 'o', '5', '5', '5', '5', '5', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', '3', '3', '3', 'o', 'o', 'o']
[('two_space', slice(10, 12, None)), ('three_space1', slice(43, 46, None)), ('three_space2', slice(16, 19, None)), ('four_space', slice(12, 16, None)), ('five_space', slice(20, 25, None))]
>>>

相关问题 更多 >