<p>我可以想出两种方法来做到这一点,但我不确定备选方案1在从左到右的意义上是否正确。最好写几个测试来检查它的行为是否正确。你知道吗</p>
<h2>备选方案1:使用regex</h2>
<p>(现在你有两个问题?:P)</sup></p>
<pre><code>import re
def transform(input_string, substitutions):
pattern = "|".join(sorted(substitutions.keys(), key = lambda x: len(x)))
def replacement(match):
return substitutions[match.group(0)]
subs = 1
while subs > 0:
input_string, subs = re.subn(pattern, replacement, input_string)
return input_string
s = {
'11': '++--',
'01': '-+-+-',
'000': '+-++++++',
'001': '--',
'100': '--+-',
'101': '----++-+--'
}
print(transform('110011111000011010110011', s))
</code></pre>
<p>它将所有按长度排序的键连接到一个<code>or</code>(<code>|</code>),因此它应该首先替换最短的键。然后它就会替换,直到找到更多为止。它适用于你的案件,但我不确定它如何处理更复杂的案件。你知道吗</p>
<h2>备选方案2:使用函数工具.reduce你知道吗</h2>
<pre><code>from functools import reduce
s = {
'11': '++--',
'01': '-+-+-',
'000': '+-++++++',
'001': '--',
'100': '--+-',
'101': '----++-+--'
}
def partial_transform(accumulator,bit):
blob, result = accumulator
next_blob = blob + bit
if next_blob in s.keys():
return ('', result + s[next_blob])
return (next_blob, result)
print(reduce(partial_transform, '110011111000011010110011', ('','')))
</code></pre>
<p>这种方法类似于其他答案,因为它从左边“吃”,直到找到匹配项,然后将其添加到结果中,直到输入结束。你知道吗</p>