Skip to main content
Code Review

Return to Revisions

1 of 4
200_success
  • 145.6k
  • 22
  • 190
  • 479

Bugs

Your program produces these erroneous results:

  • 2,0,5,5,5,5,5,5,5Impossible

    Due to tests like if hrs[0], if hrs[1], if mins[1], and if secs[1], hours, minutes, or seconds is a multiple of 10, or if the hour starts with 0.

  • 2,4,5,5,5,5,5,5,524:55:55

    The challenge states that 24:00:00 is the upper bound.

Algorithm

There is no need to implement bubbleSort. Just call sorted(seq_a, reverse=True). (By PEP 8 naming conventions, the function should be named bubble_sort.)

Your code is repetitive: you write a similar for loop to handle each of the six digits. You should generalize them to be handled by one loop, which accepts different upper limits for each digit. Note that you use <= tests for most of those loops, but < 6 for some loops — the inconsistency is confusing.

Suggested solution

I would define a placewise_max function to generalize all of your loops, then call it with three limiting template strings. Instead of loops with break statements, though, I would use next() with a generator expression.

Note that there is no need to parse each character as a numeric digit: ASCII comparison will work just as well.

def placewise_max(max_template, pool):
 """
 Try to form the lexicographically greatest string from the characters in
 the pool, where the character in each position of the output does not
 exceed the character at the corresponding position in the template.
 Return the empty string if any position cannot be filled.
 
 >>> placewise_max('91210', list('02301'))
 '31200'
 >>> placewise_max('elmo', 'abcdefghijklm')
 'elmk'
 >>> placewise_max('elmo', 'limo')
 ''
 """
 pool = sorted(pool, reverse=True)
 output = []
 try:
 for t in max_template:
 char = next(c for c in iter(pool) if c <= t)
 pool.remove(char)
 output.append(char)
 return ''.join(output)
 except StopIteration: # next() failed to pick from the pool
 return ''
def max_time(digits):
 best = max(
 placewise_max('240000', digits),
 placewise_max('235959', digits),
 placewise_max('195959', digits)
 )
 if best and (best != '000000'):
 return '{0}{1}:{2}{3}:{4}{5}'.format(*best)
if __name__ == '__main__':
 print(max_time(input().split(',')) or 'Impossible')
200_success
  • 145.6k
  • 22
  • 190
  • 479
default

AltStyle によって変換されたページ (->オリジナル) /