def solve(sequence):
def select(shift=0):
for start in range(4):
selection = sequence[start:][shift:5]
value = min(selection)
shift += selection.index(value)
yield value
return ''.join(select())
print(solve('13321311')) # 1111
print(solve('12312321')) # 1121
print(solve('33211213')) # 1113
print(solve('12345678')) # 1234
print(solve('21221132')) # 1112