📣 黑五网一特惠|VIP一年通行证5折,蓝莓、Offer多多同步特惠
12
返回列表 发新帖
楼主: 巫山云似盖
跳转到指定楼层
上一主题 下一主题
收起左侧

跪后捂胸口贡献一个Square电面。附照片

🔗
johnnywsd 2017-1-25 15:18:23 | 只看该作者
全局:
  1. # -*- coding: utf-8 -*-


  2. class Cells:
  3.     def __init__(self, height, width):
  4.         self.height = height
  5.         self.width = width
  6.         self.max_idx = height * width - 1

  7.     def get_neighbours(self, idx):
  8.         col, row = self._idx_cord(idx)
  9.         up = (col, row - 1)
  10.         right_1 = (col + 1, row)
  11.         left_1 = (col - 1, row)
  12.         if col % 2 == 0:
  13.             right_2 = (col + 1, row - 1)
  14.             left_2 = (col - 1, row - 1)
  15.         else:
  16.             right_2 = (col + 1, row + 1)
  17.             left_2 = (col - 1, row + 1)
  18.         down = (col, row + 1)
  19.         lefts = sorted([left_1, left_2], key=lambda x: -x[1])
  20.         rights = sorted([right_1, right_2], key=lambda x: x[1])
  21.         res = [self._cord_idx(*cord) for cord in [up] + rights + [down] + lefts]
  22.         return res

  23.     def _idx_cord(self, idx):
  24.         if idx > self.max_idx or idx < 0:
  25.             raise Exception
  26.         else:
  27.             col = idx // self.height
  28.             row = idx % self.height
  29.         return (col, row)

  30.     def _cord_idx(self, col, row):
  31.         if not (0 <= col < self.width and 0 <= row < self.height):
  32.             return -1
  33.         res = self.height * col + row
  34.         if res > self.max_idx:
  35.             return -1
  36.         return res

复制代码

  1. import unittest
  2. from solution import Cells


  3. class Tests(unittest.TestCase):

  4.     def test_1(self):
  5.         height = 3
  6.         width = 4
  7.         index = 4
  8.         cells = Cells(height, width)
  9.         res = cells.get_neighbours(index)
  10.         print res

  11.     def test_2(self):
  12.         height = 3
  13.         width = 4
  14.         index = 3
  15.         cells = Cells(height, width)
  16.         res = cells.get_neighbours(index)
  17.         print res

  18.     def test_3(self):
  19.         height = 3
  20.         width = 4
  21.         index = 8
  22.         cells = Cells(height, width)
  23.         res = cells.get_neighbours(index)
  24.         print res

  25. if __name__ == '__main__':
  26.     unittest.main(verbosity=2)
复制代码
回复

使用道具 举报

全局:
您好!
本帖隐藏的内容需要积分高于 100 才可浏览
您当前积分为 0。
使用VIP即刻解锁阅读权限或查看其他获取积分的方式
游客,您好!
本帖隐藏的内容需要积分高于 100 才可浏览
您当前积分为 0。
VIP即刻解锁阅读权限 或 查看其他获取积分的方式
Unlock interview details and practice with AI
Popular Interview Questions from Top Companies
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表