Tiny System design

Jimmy (xiaoke) Shen
2 min readApr 3, 2020

--

TinyURL

535. Encode and Decode TinyURL

alphabet = string.ascii_letters + '0123456789'
class Codec:

def __init__(self):
self.long_short = {}
self.short_long = {}
def encode(self, longUrl):
while longUrl not in self.long_short:
while True:
short = ''.join(random.choice(alphabet) for _ in range(6))
if short not in self.short_long:break
self.short_long[short] = longUrl
self.long_short[longUrl] = short
return 'http://' + short
def decode(self, shortUrl):
if shortUrl[-6:] not in self.short_long:return ""
return self.short_long[shortUrl[-6:]]
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))

Design a snake game

353. Design Snake Game

class SnakeGame:def __init__(self, width: int, height: int, food: List[List[int]]):
"""
Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].
"""
self.R = height
self.C = width
self.food = food[::-1]
self.dire = {'U':(-1,0),'D':(1,0),'L':(0,-1),'R':(0,1)}
self.snake = collections.deque([(0,0)])
def move(self, direction: str) -> int:
"""
Moves the snake.
@param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down
@return The game's score after the move. Return -1 if game over.
Game over when snake crosses the screen boundary or bites its body.
"""
di, dj = self.dire[direction]
i, j = self.snake[-1]
r, c = i+di, j+dj
if r<0 or r>=self.R or c<0 or c>=self.C:return -1
elif self.food and [r,c]==self.food[-1]:
self.food.pop()
self.snake.append((r,c))
return len(self.snake)-1
elif (r,c) !=self.snake[0] and (r,c) in self.snake:
return -1
else:
self.snake.popleft()
self.snake.append((r,c))
return len(self.snake)-1
# Your SnakeGame object will be instantiated and called as such:
# obj = SnakeGame(width, height, food)
# param_1 = obj.move(direction)

Programing tips

collections.deque can not slice however, it can be visited by index

>>> import collections
>>> a = collections.deque([1,2,3,4])
>>> a[1:]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence index must be integer, not 'slice'
>>> a[0]
1
>>> a[-1]
4
>>>

--

--

No responses yet