import os blocks_world_size = 10 commands = """ move 1 onto 2 move 5 onto 1 move 9 onto 5 move 8 onto 9 move 6 onto 1 move 2 onto 4 """ # initialize the table table = [ [x] for x in range(blocks_world_size) ] # initialize the map of where in the table the blocks are block_map = dict(zip(range(blocks_world_size), range(blocks_world_size))) def move_block(location1, location2): block_stack1 = table[location1] block_stack2 = table[location2] block = block_stack1.pop() block_stack2.append(block) block_map[block] = location2 def peek(stack): stack_len = len(stack) if stack_len > 0: return stack[stack_len - 1] else: return None def clear_block(block): block_table_location = block_map.get(block) if block_table_location is not None: block_stack = table[block_table_location] while len(block_stack) > 0: top_block = peek(block_stack) if top_block != block: move_block(block_table_location, top_block) else: return block_table_location return None def make_move(block1, block2): block2_location = clear_block(block2) block1_location = clear_block(block1) if block1_location is not None and block2_location is not None: move_block(block1_location, block2_location) print table else: print 'Illegal move' def run_command(command): print command if len(command) > 0: move = command.split() if len(move) == 4: if move[0] == 'move': block1 = int(move[1]) if move[2] == 'onto': block2 = int(move[3]) make_move(block1, block2) for command in commands.split(os.linesep): run_command(command)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question