gpt4 book ai didi

Python 字符串分词和递归

转载 作者:行者123 更新时间:2023-11-28 16:32:47 27 4
gpt4 key购买 nike

我正在尝试创建一个接受输入的代码(下面的示例)

Input:
BHK158 VEHICLE 11
OIUGHH MOTORCYCLE 34.46
BHK158 VEHICLE 12.000
TRIR TRUCK 2.0
BLAS215 MOTORCYCLE 0.001
END

并生成一个输出,其中列出了每个车牌号,总成本列在旁边(示例如下)

Corresponding output:
OIUGHH: 5.8582
BHK158: 5.75
TRIR: 2.666
BLAS215: 0.00017

车辆牌照每公里收费 0.25 美元(公里为输入列表中的数值),卡车每公里收费 1.333 美元,摩托车每公里收费 0.17 美元。输出按降序排列。

到目前为止,这是我的代码:

fileinput = input('Input: \n')
split_by_space = fileinput.split(' ')

vehicles = {}


if split_by_space[1] == 'VEHICLE':
split_by_space[2] = (float(split_by_space[2]) * 0.25)
elif split_by_space[1] == 'TRUCK':
split_by_space[2] = float(split_by_space[2]) * 1.333
elif split_by_space[1] == 'MOTORCYCLE':
split_by_space[2] = float(split_by_space[2]) * 0.17

if split_by_space[0] in vehicles:
previousAmount = vehicles[split_by_space[0]]
vehicles[split_by_space[0]] = previousAmount + split_by_space[2]
else:
vehicles[split_by_space[0]] = split_by_space[2]

谢谢,任何帮助/提示将不胜感激。

最佳答案

通过你的代码我注意到了一些事情,python 中的列表索引从 0 而不是 1 开始,所以你会遇到一堆越界错误。其次,输入只接受输入的第一行,所以它永远不会超过第一行。 .split() 默认按 \n 拆分文本,您必须指定是否要按其他内容(如空格)拆分。

test.txt内容:

BHK158 VEHICLE 11
OIUGHH MOTORCYCLE 34.46
BHK158 VEHICLE 12.000
TRIR TRUCK 2.0
BLAS215 MOTORCYCLE 0.001

python代码:

fileinput = open('test.txt', 'r')
lines = fileinput.readlines()

vehicles = {}

for line in lines:
split_by_space = line.split(' ')
if split_by_space[1] == "VEHICLE":
split_by_space[2] = (float(split_by_space[2]) * 0.25)
elif split_by_space[1] == "TRUCK":
split_by_space[2] = float(split_by_space[2]) * 1.333
elif split_by_space[1] == "MOTORCYCLE":
split_by_space[2] = float(split_by_space[2]) * 0.17


if split_by_space[0] in vehicles:
previousAmount = vehicles[split_by_space[0]]
vehicles[split_by_space[0]] = previousAmount + split_by_space[2]
else:
vehicles[split_by_space[0]] = split_by_space[2]

输出:

{'BLAS215': 0.00017, 'OIUGHH': 5.858200000000001, 'TRIR': 2.666, 'BHK158': 5.75}

关于Python 字符串分词和递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30309687/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com