from __future__ import print_function

def run_utm(
        state = None,
        blank = None,
        rules = [],
        tape = [],
        halt = None,
        pos = 0):
    st = state
    if not tape: tape = [blank]
    if pos < 0: pos += len(tape)
    if pos >= len(tape) or pos < 0: raise Error( )
    rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)

    while True:
        print(st, '\t', end=)
        for i, v in enumerate(tape):
            if i == pos: print(% (v,), end=)
            else: print(v, end=)
        print()

        if st == halt: break
        if (st, tape[pos]) not in rules: break

        (v1, dr, s1) = rules[(st, tape[pos])]
        tape[pos] = v1
        if dr == 'left':
            if pos > 0: pos -= 1
            else: tape.insert(0, blank)
        if dr == 'right':
            pos += 1
            if pos >= len(tape): tape.append(blank) 
        st = s1




print()
run_utm(
    halt = 'qf',
	state = 'q0',
	tape = list(),
	blank = 'B',
	rules = map(tuple, 
               [.split(),
		        .split()]
        )
    )

print()
run_utm(
    halt = 'halt',
	state = 'a',
	blank = '0',
	rules = map(tuple,
        [.split(),
         .split(),
         .split(),
         .split(),
         .split(),
         .split()]
        )
    )

print()
run_utm(halt = 'STOP',
	state = 'A',
	blank = '0',
	tape = .split(),
	rules = map(tuple,
       [.split(),
		.split(),
		.split(),
		.split(),
		.split(),
		.split(),
		.split(),
		.split(),
		.split(),
		.split(),
		.split(),
		.split(),
		.split(),
		.split()]
        )
    )