import sys NL = 0; SP = 1; OTHER = 2; EOF = 3 # character types char_to_type = { '' : EOF, '\n' : NL, ' ' : SP } BEFORE = 0; INSIDE = 1; AFTER = 2; END = 3 # FSM states transitions = [ # NL SP OTHER EOF [ [ BEFORE, True ], [ BEFORE, False ], [ INSIDE, True ], [ END, False ] ], # BEFORE [ [ BEFORE, True ], [ AFTER, False ], [ INSIDE, True ], [ END, False ] ], # INSIDE [ [ BEFORE, True ], [ AFTER, False ], [ AFTER, False ], [ END, False ] ], # AFTER ] state = BEFORE while state != END: c = sys.stdin.read(1) ctype = char_to_type[c] if c in char_to_type else OTHER nextState, printChar = transitions[state][ctype] if printChar: sys.stdout.write(c) state = nextState