会给你一个列表,有四个数,[2,3,1,6]
你需要做的是,把这四个数字组成一个时间格式,并使得这个时间是所有组合中最晚的组合。
例如[2,3,1,6]可以组成,13:26,16:23等等,但是最晚的时间是23:16。所以请返回23:16这个结果。
如果四个数无法组成时间格式,返回""。
答案一样会延迟放出。你猜我到底是会还是不会呢?
测试代码如下,test.py还是请去33,34中寻找。
- test.assert_equals(late_clock([9, 1, 2, 5]), '21:59')
- test.assert_equals(late_clock([0, 2, 2, 2]), '22:20')
- test.assert_equals(late_clock([9, 0, 1, 1]), '19:10')
- test.assert_equals(late_clock([2, 3, 2, 4]), '23:42')
- test.assert_equals(late_clock([1, 2, 8, 9]), '19:28')
- test.assert_equals(late_clock([4, 7, 8, 9]), '')
这么多大佬发过了,我也发个我的吧。就不设置隐藏了。
- def late_clock(digits):
- """
- 有四个数,[2,3,1,6],把这四个数字组成一个时间格式,并使得这个时间是所有组合中最晚的组合。
- """
- from itertools import permutations
- temp = sorted([each[:2]+":"+each[2:] for each in [''.join(map(str, each)) for each in list(permutations(digits))]])
- result = []
- for each in temp:
- if int(each[0:2]) < 24 and int(each[3:]) < 60:
- result.append(each)
- return result[-1] if result else ''
再发送几个评分比较高的代码。给大家参考。
- 这是和我比较相似的,筛选类的。
- from itertools import permutations
- def late_clock(digits):
- for p in permutations(sorted(digits, reverse=True)):
- if p[0] > 2 or (p[0] == 2 and p[1] > 3) or p[2] > 5: continue
- return '{}{}:{}{}'.format(*p)
- 这是正则筛选的。
- import re
- from itertools import permutations
- def late_clock(digits):
- s = max(a for a in (''.join(map(str, a)) for a in permutations(digits)) if re.fullmatch(r'(?:2[0-3]|[01]d)[0-5]d', a))
- return '%s:%s' % (s[:2], s[2:])
- 这是递归式的。我自己最开始写的也是一个递归式的。但是无法通过[1,2,8,9]这种组合,不过这位完成了,不过从代码上面来看,不太好懂。
- def late_clock(digits):
- def loc_num(arr, n):
- req_num = req_idx = -1
- for k in range(len(arr)):
- if arr[k] <= n:
- if arr[k] >= req_num:
- req_num = arr[k]
- req_idx = k
- arr[req_idx] = -1
- return req_num
- from copy import deepcopy
- digits_copy = deepcopy(digits)
- t = [0] * 4
- nl = [2, 3, 5, 9]
- for i in range(len(nl)):
- if i == 1:
- t[i] = loc_num(digits, nl[i]) if t[i - 1] == nl[i - 1] else loc_num(digits, nl[i] ** 2)
- else:
- t[i] = loc_num(digits, nl[i])
- if min(t) < 0:
- nl = [1, 9, 5, 9]
- t = [loc_num(digits_copy, nl[i]) for i in range(len(nl))]
- return '%s%s:%s%s' % (t[0], t[1], t[2], t[3])
- 还有这种,使用datetime进行格式筛选的。也是不错的方法。
- from datetime import time
- from itertools import permutations
- def late_clock(digits):
- ret = []
- for ll in permutations(digits):
- try:
- hr = ll[0] * 10 + ll[1]
- mm = ll[2] * 10 + ll[3]
- ret.append(time(hr, mm))
- except ValueError: pass
- return max(ret).strftime('%H:%M')