-
-
Save fkztw/d11689c1fd6aed641fb5d351b64ada3f to your computer and use it in GitHub Desktop.
說到比對就想到 regexp....
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Given cyclic list with elements integers. | |
Find the smallest cycle. | |
>>> find_smallest_cycle([10, 3, 999, 24, 10, 3, 999, 24, 10, 3]) | |
[10, 3, 999, 24] | |
""" | |
def origin(mylist): | |
def make_tuple(list_a): | |
return list(set(map(tuple,list_a))) | |
for i in range(1, len(mylist)+1): | |
ans_list = [mylist[j:j+i] for j in range(0,len(mylist), i)] | |
if len(ans_list) == 1: | |
return ans_list[0] | |
if (len(make_tuple(ans_list[:-1])) == 1 | |
and ans_list[0][0:len(ans_list[-1])] == ans_list[-1]): | |
return ans_list[0] | |
def with_regexp(given_list): | |
import re | |
s = ' '.join(map(str, given_list)) | |
m = re.match(r'^((.+?)[ \d]*?)(?: \1)* \2$|^(.+?)(?: \3)*$', s) | |
return list(map(int, (m.group(1) or m.group(3)).split(' '))) | |
in_oneline = lambda L: list(map(int,next(i for i in __import__("re").match(r'^((.+?)[ \d]*?)(?: \1)* \2$|^(.+?)(?: \3)*$',' '.join(map(str,L))).groups()if i).split(' '))) | |
TEST_DATA = ( | |
([1], [1]), | |
([1], [1,1]), | |
([1], [1,1,1,1,1]), | |
([1,1,1,1,1,2], [1,1,1,1,1,2]), | |
([1,2], [1,2,1,2,1,2]), | |
([1,2], [1,2,1,2,1,2,1,2,1]), | |
([1,2,3], [1,2,3]), | |
([1,2,3], [1,2,3,1,2]), | |
([1,2,3], [1,2,3,1,2,3]), | |
([1,2,3], [1,2,3,1,2,3,1,2]), | |
) | |
solutions = ( | |
origin, | |
with_regexp, | |
in_oneline, | |
) | |
for find_smallest_cycle in solutions: | |
for cycle, given_list in TEST_DATA: | |
assert cycle == find_smallest_cycle(given_list) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment