<s> from __future__ import with_statement <EOL> try : <EOL> import simplejson as json <EOL> json <EOL> except ImportError : <EOL> import json <EOL> qwerty = r'''<STR_LIT>''' <EOL> dvorak = r'''<STR_LIT>''' <EOL> keypad = r'''<STR_LIT>''' <EOL> mac_keypad = r'''<STR_LIT>''' <EOL> def get_slanted_adjacent_coords ( x , y ) : <EOL> '''<STR_LIT>''' <EOL> return [ ( x - <NUM_LIT:1> , y ) , ( x , y - <NUM_LIT:1> ) , ( x + <NUM_LIT:1> , y - <NUM_LIT:1> ) , ( x + <NUM_LIT:1> , y ) , ( x , y + <NUM_LIT:1> ) , ( x - <NUM_LIT:1> , y + <NUM_LIT:1> ) ] <EOL> def get_aligned_adjacent_coords ( x , y ) : <EOL> '''<STR_LIT>''' <EOL> return [ ( x - <NUM_LIT:1> , y ) , ( x - <NUM_LIT:1> , y - <NUM_LIT:1> ) , ( x , y - <NUM_LIT:1> ) , ( x + <NUM_LIT:1> , y - <NUM_LIT:1> ) , ( x + <NUM_LIT:1> , y ) , ( x + <NUM_LIT:1> , y + <NUM_LIT:1> ) , ( x , y + <NUM_LIT:1> ) , ( x - <NUM_LIT:1> , y + <NUM_LIT:1> ) ] <EOL> def build_graph ( layout_str , slanted ) : <EOL> '''<STR_LIT>''' <EOL> position_table = { } <EOL> tokens = layout_str . split ( ) <EOL> token_size = len ( tokens [ <NUM_LIT:0> ] ) <EOL> x_unit = token_size + <NUM_LIT:1> <EOL> adjacency_func = get_slanted_adjacent_coords if slanted else get_aligned_adjacent_coords <EOL> assert all ( len ( token ) == token_size for token in tokens ) , '<STR_LIT>' + layout_str <EOL> for y , line in enumerate ( layout_str . split ( '<STR_LIT:\n>' ) ) : <EOL> slant = y - <NUM_LIT:1> if slanted else <NUM_LIT:0> <EOL> for token in line . split ( ) : <EOL> x , remainder = divmod ( line . index ( token ) - slant , x_unit ) <EOL> assert remainder == <NUM_LIT:0> , '<STR_LIT>' % ( token , layout_str ) <EOL> position_table [ ( x , y ) ] = token <EOL> adjacency_graph = { } <EOL> for ( x , y ) , chars in position_table . iteritems ( ) : <EOL> for char in chars : <EOL> adjacency_graph [ char ] = [ ] <EOL> for coord in adjacency_func ( x , y ) : <EOL> adjacency_graph [ char ] . append ( position_table . get ( coord , None ) ) <EOL> return adjacency_graph <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> with open ( '<STR_LIT>' , '<STR_LIT:w>' ) as f : <EOL> out = { } <EOL> for graph_name , args in [ ( '<STR_LIT>' , ( qwerty , True ) ) , <EOL> ( '<STR_LIT>' , ( dvorak , True ) ) , <EOL> ( '<STR_LIT>' , ( keypad , False ) ) , <EOL> ( '<STR_LIT>' , ( mac_keypad , False ) ) ] : <EOL> graph = build_graph ( * args ) <EOL> out [ graph_name ] = graph <EOL> json . dump ( out , f ) </s>
