首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何随机化切片?

如何随机化切片?
EN

Stack Overflow用户
提问于 2016-12-03 10:15:52
回答 1查看 46关注 0票数 0

我正在尝试制作战列舰,我正在制作一个列表中的船“板”,船的长度将由切片决定。我试着用random.choice来移动船,但是我很快意识到random.choice一次只移动一个元素,但是船有2-5个元素。我正在尝试看看是否可以将列表中的切片随机化为在切片上分配的单位。random.shuffle似乎不起作用。

代码语言:javascript
复制
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]
EN

回答 1

Stack Overflow用户

发布于 2016-12-03 12:38:11

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

代码语言:javascript
复制
occupied = set()

定义规范

代码语言:javascript
复制
N = 49
board = ['o'] * N
ship_specs = [('two_space', 2), ('three_space1', 3), ('three_space2', 3),
              ('four_space', 4), ('five_space', 5)]

开始造船-使用collections.namedtuple定义船

代码语言:javascript
复制
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))]
>>>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40943569

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档