我似乎无法在以下方面找到有效的答案:
假设我有以下返回的 LONG int(或与此相关的任何字符串):
longnr = 26731623516244147357200698985770699644500911065919594945175038371437093557337774208653
我可以通过以下方式轻松拆分:
splitnr = [26731,62351,624,41,4735,720,0698,9857,7069,964,450,091,10659,195,94,94517,5038,3714,3709,35,573,37,7,74208653]
每个组合都是独一无二的,因此没有重复的数字。 我用简单的代码来做到这一点,只需遍历每个项目并将它们添加到一个字符串中,直到它找到一个重复的数字。然后只需将此字符串写入列表,空字符串,添加刚刚检查的数字并继续直到完成所有。
我想要的是它会采用尽可能少的组合。 因此,首先尝试找到所有 10 位唯一组合,然后找到剩余的 9、8、7 等
我需要正则表达式吗? 我无法完成这项工作,有人建议我需要巨大的模式。
下一个选项:
len(set(str(longnr)[0:10])) == len(str(longnr)[0:10])
这适用于前 10 个以检查它是否唯一。
我如何以最佳方式离开这里?
必须像在 splitnr 中一样保持顺序。
最佳答案
我确信爱德华·彼得斯找到了答案。但根据经验,这三种解决方案似乎都同样好:
from random import choice
def edward_peters(string):
sequences = [[]]
for end in range(1, len(string) + 1):
def candidate_sequences():
for previous_end in range(max(0, end - 10), end):
substring = string[previous_end:end]
if len(substring) == len(set(substring)):
yield sequences[previous_end] + [substring]
sequences.append(min(candidate_sequences(), key=len))
return sequences[-1]
def brendan_abel(long_string):
if not long_string:
return []
cur_i = None
cur_s = None
max_i = None
max_s = None
for i, s in enumerate(long_string):
if cur_s is None or s in cur_s:
if cur_s and (max_s is None or len(cur_s) > len(max_s)):
max_i = cur_i
max_s = cur_s
cur_i = i
cur_s = [s]
else:
cur_s.append(s)
else:
if cur_s and (max_s is None or len(cur_s) > len(max_s)):
max_i = cur_i
max_s = cur_s
before = long_string[:max_i]
after = long_string[max_i + len(max_s):]
return brendan_abel(before) + [''.join(max_s)] + brendan_abel(after)
def ruud(string):
result = []
current = ''
for c in string:
if c in current:
result.append(current)
current = c
else:
current += c
result.append(current)
return result
def main():
while True:
string = ''.join(choice('1234567890') for _ in range(10000))
results = [func(string) for func in [edward_peters, brendan_abel, ruud]]
assert all(''.join(result) == string for result in results)
assert len(set(map(len, results))) == 1
main()
我根本无法直观地把握这一点。似乎 Brendan Abel 是正确的,Edward Peters 的解决方案是 OP 的倒退,例如
print edward_peters(string)
['49', '9', '3849', '3089', '91', '1', '15', '58', '42876', '81926', '6720', '90', '0', '27103', '3064', '436', '6', '862', '2', '201', '7091', '912', '23', '6345', '582', '382', '2', '82457', '64937', '0574', '2743', '983', '4382']
关于python - 按独特模式拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37264479/