首页 > 解决方案 > 如何将 str "oneninetwoninenine" 转换为 19299

问题描述

大家好,我正在解决一个问题,似乎无法获得正确的输出。问题是:给定一个拼写为数字的字符串,返回您可以使用所有字符作为字符串创建的最小数字,例如输入是“onenine”,输出应该是“19”,另一个例子是,输入是“oneoneninetwo”,输出应该是“1192”,因为您可以从输入字符串创建字符串“one”“two”“nine”“nine”。

到目前为止,这是我的代码,它在某些情况下不起作用:假设输入是“oneninetwoninenine”输出是“129”而不是预期的输出应该是“12999”

def canConstruct(string, array, memo = dict()):
    if string in memo:
        return memo[string]
    if string == "":
        return 1
    count = None
    for st in array:
        if string.startswith(st):
            size = len(st)
            if canConstruct(string[size::],array) == 1:
                if count == None:
                    count = 1
                else:
                    count += 1
                memo[string] = True
                return memo[string]
    memo[string] = False
    return False

def integerConvert(array):
    numbers = ['zero','one','two','three','four','five','six','seven','eight','nine']
    numbersCache = {'zero':0,'one':0,'two':0,'three':0,'four':0,'five':0,'six':0,'seven':0,'eight':0,'nine':0}
    numbersRef = {'zero':0,'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9}

    for num in numbers:
        if canConstruct(num,array):
            for char in num:
                array.replace(char,"",1)
            numbersCache[num] += 1
    result = ""
    print(numbersCache)
    for key,value in numbersCache.items():
        result += (str(numbersRef[key]) * value)
    return result
            
print(integerConvert('oneninetwoninenine'))

标签: pythonpython-3.x

解决方案


基本分解任务,或“标记化”任务。这是来自正式语言的主题(也是编译器构造)。

通常,您可能需要“(第一个)最长匹配”分析,也称为“ Maximal munch ”,以防可能有多个匹配,编程语言就是这种情况,当您尝试确定123.456是整数还是浮点数时点号(3 长前缀是一个整数......但有一个更长的前缀)。

words = {
    'zero': '0', 'one': '1', 'two': '2', 'three': '3', 'four': '4',
    'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9'}

def analyze(source):
    analysis = []
    while source: # or: len(source) > 0
        viable_prefixes = [
            prefix for prefix in words
            if source.startswith(prefix)]
        
        if not viable_prefixes:
            raise ValueError("can't tokenize remainder", analysis, source)

        prefix = max(viable_prefixes, key=len) # maximal munch

        analysis.append(words[prefix])

        source = source.removeprefix(prefix) # Python 3.9+
        # source = source[len(prefix):] # before Python 3.9
    
    return analysis

inputs = '''
    oneninetwoninenine
'''.split()

for inpt in inputs:
    print(">>>", inpt)
    output = analyze(inpt)
    print(output)

>>> oneninetwoninenine
['1', '9', '2', '9', '9']

推荐阅读