新农上路
- 积分
- 99
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2011-11-7
- 最后登录
- 1970-1-1
|
- # -*- coding: utf-8 -*-
- class Cells:
- def __init__(self, height, width):
- self.height = height
- self.width = width
- self.max_idx = height * width - 1
- def get_neighbours(self, idx):
- col, row = self._idx_cord(idx)
- up = (col, row - 1)
- right_1 = (col + 1, row)
- left_1 = (col - 1, row)
- if col % 2 == 0:
- right_2 = (col + 1, row - 1)
- left_2 = (col - 1, row - 1)
- else:
- right_2 = (col + 1, row + 1)
- left_2 = (col - 1, row + 1)
- down = (col, row + 1)
- lefts = sorted([left_1, left_2], key=lambda x: -x[1])
- rights = sorted([right_1, right_2], key=lambda x: x[1])
- res = [self._cord_idx(*cord) for cord in [up] + rights + [down] + lefts]
- return res
- def _idx_cord(self, idx):
- if idx > self.max_idx or idx < 0:
- raise Exception
- else:
- col = idx // self.height
- row = idx % self.height
- return (col, row)
- def _cord_idx(self, col, row):
- if not (0 <= col < self.width and 0 <= row < self.height):
- return -1
- res = self.height * col + row
- if res > self.max_idx:
- return -1
- return res
复制代码
- import unittest
- from solution import Cells
- class Tests(unittest.TestCase):
- def test_1(self):
- height = 3
- width = 4
- index = 4
- cells = Cells(height, width)
- res = cells.get_neighbours(index)
- print res
- def test_2(self):
- height = 3
- width = 4
- index = 3
- cells = Cells(height, width)
- res = cells.get_neighbours(index)
- print res
- def test_3(self):
- height = 3
- width = 4
- index = 8
- cells = Cells(height, width)
- res = cells.get_neighbours(index)
- print res
- if __name__ == '__main__':
- unittest.main(verbosity=2)
复制代码 |
|