Last active
October 24, 2017 12:27
-
-
Save apua/4bd89c4ecebe9f8069fa 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) |
改掉 find_cycle
就行了
def find_cycle(given_list):
import re
s = ' '.join(map(str, given_list))[::-1]
m = re.match(r'^(.*?) ?(.*? \1)*$', s)
c = m.group(2) or m.group(1)
return list(map(int, c[::-1].split()))
m = re.match(r'^(.*?) ?(.*? \1)*$', s)
這行可以把 ^
拿掉
額 測資如果是 [1, 1, 3, 1]
的話會錯 囧
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
打完收工。