def colorize(string, stack):
  '''Apply optimal ANSI escape sequences to the string.'''
  codes = optimize(stack)
  if len(codes):
    prefix = SEQ % ';'.join(map(str, codes))
    suffix = SEQ % STYLE.reset
    return prefix + string + suffix
  else:
    return string
Apply optimal ANSI escape sequences to the string.