Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Separating String into Words and Recursion

I'm trying to create a code that will take in an input (example below)

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

and produce an output where each license plate number is listed and the total cost is listed beside (example below)

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

The vehicle license plates are charged $0.25 per kilometer (the kilometers are the number values in the input list), trucks are charged $1.333 per kilometer, and motorcycles $0.17 per kilometer. The output is listed in descending order.

Here is my code thus far:

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]

Thanks, any help/hints would be greatly appreciated.

like image 599
User100 Avatar asked Dec 20 '25 14:12

User100


1 Answers

Going through your code I noticed a few things, list indicies in python start at 0, not 1 so you were get a bunch of out of bounds errors. Secondly, input only takes the first line of the input so it was never going past the first line. .split() splits text by \n by default, you have to specify if you want to split by something else, like a space.

test.txt contents:

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

python code:

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]

output:

{'BLAS215': 0.00017, 'OIUGHH': 5.858200000000001, 'TRIR': 2.666, 'BHK158': 5.75}
like image 190
heinst Avatar answered Dec 22 '25 03:12

heinst



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!