python - 如何将 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'))
解决方案
基本分解任务,或“标记化”任务。这是来自正式语言的主题(也是编译器构造)。
通常,您可能需要“(第一个)最长匹配”分析,也称为“ 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']
推荐阅读
- python - 在给定特定块大小的情况下稀疏矩阵的函数
- python - 如何使用 Boto3 SDK 为 SageMaker 训练作业指定源目录和入口点?用例是通过 Lambda 调用开始训练
- bootstrap-5 - 导航中带有两个单词的引导按钮会导致第二个单词换行
- mysql - SQL 过滤掉与条件匹配的字符串,并有特定的异常通过
- xaml - 有没有办法将一个 Xamarin Forms 控件与另一个“关联”?
- django - Django get request.POST.get() 参数未按预期工作,带括号的参数名称 []
- sql - Laravel Eloquent 如何从日期范围内的 2 个表中获取数据
- r - 有没有办法为使用具有填充美学的因子变量的 ggplot 条形图提供 n 个计数?
- node.js - 如何将基于 Node js 的网站转换为移动应用程序?
- python - Python - 如何通过 Selenium 发送键发送数值