Решение на Питоните хапят! от Станимир Николов

Обратно към всички решения

Към профила на Станимир Николов

Резултати

  • 4 точки от тестове
  • 0 бонус точки
  • 4 точки общо
  • 8 успешни тест(а)
  • 5 неуспешни тест(а)

Код

class WorldRow():
def __init__(self):
self.items = dict()
def __getitem__(self, key):
return self.items.get(key, None)
def __setitem__(self, key, value):
self.items[key] = value
class World():
def __init__(self, width):
self.width = width
self.board = [WorldRow() for key in range(width)]
def __str__(self):
result = ''
for row in self.board:
for key in range(self.width):
cell = row[key]
if cell:
result += "{}".format(cell.__str__())
else:
result += "."
result += '\n'
return result
def __len__(self):
return self.width
def __getitem__(self, key):
return self.board[key]
class Cell():
def __init__(self, contents=None):
self.contents = contents
def is_empty(self):
if self.contents is None:
return True
else:
return False
def __str__(self):
if self.is_empty():
return ","
else:
return self.contents.__str__()
class WorldObject():
pass
class Food(WorldObject):
def __init__(self, energy=0):
self.energy = energy
def __str__(self):
return str(self.energy)
class PythonPart(WorldObject):
def __str__(self):
return '#'
class PythonHead(WorldObject):
def __str__(self):
return '@'
class Vec2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(a, b):
if isinstance(a, Vec2D) and isinstance(b, Vec2D):
return a.x == b.x and a.y == b.y
raise Exception('Bad parameters in Vec2D __eq__')
def __add__(a, b):
if isinstance(a, Vec2D) and isinstance(b, Vec2D):
return Vec2D(a.x + b.x, a.y + b.y)
raise Exception('Bad parameters in Vec2D __add__')
def __sub__(a, b):
if isinstance(a, Vec2D) and isinstance(b, Vec2D):
return Vec2D(a.x - b.x, a.y - b.y)
raise Exception('Bad parameters in Vec2D __add__')
def __mul__(a, b):
if isinstance(a, Vec2D) and isinstance(b, int):
return Vec2D(a.x*b, a.y*b)
if isinstance(b, Vec2D) and isinstance(a, int):
return Vec2D(b.x*a, b.y*a)
raise Exception('Bad parameters in Vec2D __mul__')
def __neg__(self):
if isinstance(self, Vec2D):
return Vec2D(-self.x, -self.y)
return -self
class Death(Exception):
pass
class Python:
LEFT = Vec2D(0, -1)
RIGHT = Vec2D(0, 1)
UP = Vec2D(1, 0)
DOWN = Vec2D(-1, 0)
def __init__(self, world, coords, size, direction):
self.world = world
self.coords = coords
self.size = size
self.direction = direction
self.energy = 0
self.head = None
self.body_parts_cells = []
self.initial_python_pacement()
def is_coord_in_the_map(self, coord):
first_cond = coord.x < 0 or coord.x >= len(self.world)
second_cond = coord.y < 0 or coord.y >= len(self.world)
if first_cond or second_cond:
raise Death("deth map")
def if_coord_over_a_python(self, coord):
cell = self.world[coord.x][coord.y]
if cell and isinstance(cell.contents, (PythonHead, PythonPart)):
raise Death("deth python")
def is_there_food_on_coord(self, coord):
first_cond = coord.x >= 0 or coord.x < len(self.world)
second_cond = coord.y >= 0 or coord.y < len(self.world)
if first_cond and second_cond:
cell = self.world[coord.x][coord.y]
if cell:
return isinstance(cell.contents, Food)
return False
def set_python_part_at_position(self, part, position):
self.is_coord_in_the_map(position)
self.if_coord_over_a_python(position)
cell = self.world[position.x][position.y]
if cell:
cell.contents = part
else:
self.world[position.x][position.y] = Cell(part)
def initial_python_pacement(self):
self.head = PythonHead()
self.set_python_part_at_position(self.head, self.coords)
for body_part_number in range(1, self.size + 1):
position = self.direction*(-1)*body_part_number + self.coords
self.set_python_part_at_position(PythonPart(), position)
self.body_parts_cells.append(position)
self.last_part_position = position
def move(self, direction):
if self.direction*(-1) == direction:
raise ValueError('value error')
self.direction = direction
prev_coords = self.coords
self.coords = self.coords + self.direction
is_there_food = self.is_there_food_on_coord(self.coords)
new_food_energy = 0
if is_there_food:
food = self.world[self.coords.x][self.coords.y].contents
new_food_energy = food.energy
new_head = PythonHead()
self.set_python_part_at_position(new_head, self.coords)
self.head = new_head
if self.size > 0:
part_after_head = PythonPart()
self.world[prev_coords.x][prev_coords.y].contents = part_after_head
self.body_parts_cells.insert(0, prev_coords)
if is_there_food:
self.energy += new_food_energy
self.size += 1
else:
last_coord = self.body_parts_cells.pop()
self.world[last_coord.x][last_coord.y].contents = None
self.world[last_coord.x][last_coord.y] = None

Лог от изпълнението

...EEE....FF.
======================================================================
ERROR: test_python_movement_basic (test.PythonTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20130606-14014-5qz1r2/test.py", line 30, in test_python_movement_basic
    x, y = Vec2D(10, 10) + direction
TypeError: 'Vec2D' object is not iterable

======================================================================
ERROR: test_python_placement (test.PythonTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20130606-14014-5qz1r2/test.py", line 18, in test_python_placement
    x, y = position - direction
TypeError: 'Vec2D' object is not iterable

======================================================================
ERROR: test_snake_death (test.PythonTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20130606-14014-5qz1r2/test.py", line 59, in test_snake_death
    py2 = Python(world, Vec2D(8, 5), 3, Python.UP)
  File "/tmp/d20130606-14014-5qz1r2/solution.py", line 133, in __init__
    self.initial_python_pacement()
  File "/tmp/d20130606-14014-5qz1r2/solution.py", line 169, in initial_python_pacement
    self.set_python_part_at_position(PythonPart(), position)
  File "/tmp/d20130606-14014-5qz1r2/solution.py", line 157, in set_python_part_at_position
    self.if_coord_over_a_python(position)
  File "/tmp/d20130606-14014-5qz1r2/solution.py", line 144, in if_coord_over_a_python
    raise Death("deth python")
solution.Death: deth python

======================================================================
FAIL: test_cell_invalid (test.WorldTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20130606-14014-5qz1r2/test.py", line 147, in test_cell_invalid
    badcell = Cell("snakesandladders")
AssertionError: TypeError not raised

======================================================================
FAIL: test_world_indexing (test.WorldTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lib/language/python/runner.py", line 60, in thread
    raise it.exc_info[1]
  File "lib/language/python/runner.py", line 48, in run
    self.result = func(*args, **kwargs)
  File "/tmp/d20130606-14014-5qz1r2/test.py", line 119, in test_world_indexing
    cell = world[5][1337]
AssertionError: IndexError not raised

----------------------------------------------------------------------
Ran 13 tests in 0.012s

FAILED (failures=2, errors=3)

История (1 версия и 0 коментара)

Станимир обнови решението на 15.05.2013 02:22 (преди над 11 години)

+class WorldRow():
+ def __init__(self):
+ self.items = dict()
+
+ def __getitem__(self, key):
+ return self.items.get(key, None)
+
+ def __setitem__(self, key, value):
+ self.items[key] = value
+
+
+class World():
+
+ def __init__(self, width):
+ self.width = width
+ self.board = [WorldRow() for key in range(width)]
+
+ def __str__(self):
+ result = ''
+ for row in self.board:
+ for key in range(self.width):
+ cell = row[key]
+ if cell:
+ result += "{}".format(cell.__str__())
+ else:
+ result += "."
+ result += '\n'
+ return result
+
+ def __len__(self):
+ return self.width
+
+ def __getitem__(self, key):
+ return self.board[key]
+
+
+class Cell():
+
+ def __init__(self, contents=None):
+ self.contents = contents
+
+ def is_empty(self):
+ if self.contents is None:
+ return True
+ else:
+ return False
+
+ def __str__(self):
+ if self.is_empty():
+ return ","
+ else:
+ return self.contents.__str__()
+
+
+class WorldObject():
+ pass
+
+
+class Food(WorldObject):
+
+ def __init__(self, energy=0):
+ self.energy = energy
+
+ def __str__(self):
+ return str(self.energy)
+
+
+class PythonPart(WorldObject):
+
+ def __str__(self):
+ return '#'
+
+
+class PythonHead(WorldObject):
+
+ def __str__(self):
+ return '@'
+
+
+class Vec2D:
+
+ def __init__(self, x, y):
+ self.x = x
+ self.y = y
+
+ def __eq__(a, b):
+ if isinstance(a, Vec2D) and isinstance(b, Vec2D):
+ return a.x == b.x and a.y == b.y
+ raise Exception('Bad parameters in Vec2D __eq__')
+
+ def __add__(a, b):
+ if isinstance(a, Vec2D) and isinstance(b, Vec2D):
+ return Vec2D(a.x + b.x, a.y + b.y)
+ raise Exception('Bad parameters in Vec2D __add__')
+
+ def __sub__(a, b):
+ if isinstance(a, Vec2D) and isinstance(b, Vec2D):
+ return Vec2D(a.x - b.x, a.y - b.y)
+ raise Exception('Bad parameters in Vec2D __add__')
+
+ def __mul__(a, b):
+ if isinstance(a, Vec2D) and isinstance(b, int):
+ return Vec2D(a.x*b, a.y*b)
+ if isinstance(b, Vec2D) and isinstance(a, int):
+ return Vec2D(b.x*a, b.y*a)
+ raise Exception('Bad parameters in Vec2D __mul__')
+
+ def __neg__(self):
+ if isinstance(self, Vec2D):
+ return Vec2D(-self.x, -self.y)
+ return -self
+
+
+class Death(Exception):
+ pass
+
+
+class Python:
+
+ LEFT = Vec2D(0, -1)
+ RIGHT = Vec2D(0, 1)
+ UP = Vec2D(1, 0)
+ DOWN = Vec2D(-1, 0)
+
+ def __init__(self, world, coords, size, direction):
+ self.world = world
+ self.coords = coords
+ self.size = size
+ self.direction = direction
+ self.energy = 0
+ self.head = None
+ self.body_parts_cells = []
+ self.initial_python_pacement()
+
+ def is_coord_in_the_map(self, coord):
+ first_cond = coord.x < 0 or coord.x >= len(self.world)
+ second_cond = coord.y < 0 or coord.y >= len(self.world)
+ if first_cond or second_cond:
+ raise Death("deth map")
+
+ def if_coord_over_a_python(self, coord):
+ cell = self.world[coord.x][coord.y]
+ if cell and isinstance(cell.contents, (PythonHead, PythonPart)):
+ raise Death("deth python")
+
+ def is_there_food_on_coord(self, coord):
+ first_cond = coord.x >= 0 or coord.x < len(self.world)
+ second_cond = coord.y >= 0 or coord.y < len(self.world)
+ if first_cond and second_cond:
+ cell = self.world[coord.x][coord.y]
+ if cell:
+ return isinstance(cell.contents, Food)
+ return False
+
+ def set_python_part_at_position(self, part, position):
+ self.is_coord_in_the_map(position)
+ self.if_coord_over_a_python(position)
+ cell = self.world[position.x][position.y]
+ if cell:
+ cell.contents = part
+ else:
+ self.world[position.x][position.y] = Cell(part)
+
+ def initial_python_pacement(self):
+ self.head = PythonHead()
+ self.set_python_part_at_position(self.head, self.coords)
+ for body_part_number in range(1, self.size + 1):
+ position = self.direction*(-1)*body_part_number + self.coords
+ self.set_python_part_at_position(PythonPart(), position)
+ self.body_parts_cells.append(position)
+ self.last_part_position = position
+
+ def move(self, direction):
+ if self.direction*(-1) == direction:
+ raise ValueError('value error')
+ self.direction = direction
+ prev_coords = self.coords
+ self.coords = self.coords + self.direction
+ is_there_food = self.is_there_food_on_coord(self.coords)
+ new_food_energy = 0
+ if is_there_food:
+ food = self.world[self.coords.x][self.coords.y].contents
+ new_food_energy = food.energy
+ new_head = PythonHead()
+ self.set_python_part_at_position(new_head, self.coords)
+ self.head = new_head
+ if self.size > 0:
+ part_after_head = PythonPart()
+ self.world[prev_coords.x][prev_coords.y].contents = part_after_head
+ self.body_parts_cells.insert(0, prev_coords)
+ if is_there_food:
+ self.energy += new_food_energy
+ self.size += 1
+ else:
+ last_coord = self.body_parts_cells.pop()
+ self.world[last_coord.x][last_coord.y].contents = None
+ self.world[last_coord.x][last_coord.y] = None