Rahul Kashyap - 1 year ago 102
Python Question

# How to get the result in single List?

I'm creating Fare Estimator on the basis of a Codefight Code challenge.

That can tell you how much your ride will cost before you request it. It works by passing approximated ride distance and ride time through this formula:

`(Cost per minute) * (ride time) + (Cost per mile) * (ride distance)`

Example

For

• ride_time = 30,

• ride_distance = 7,

• cost_per_minute = [0.2, 0.35, 0.4, 0.45]

• cost_per_mile = [1.1, 1.8, 2.3, 3.5], the output should be

• fareEstimator(ride_time, ride_distance, cost_per_minute,
cost_per_mile) = [13.7, 23.1, 28.1, 38]

Where Output must be in a list

Since:

• 30 * 0.2 + 7 * 1.1 = 6 + 7.7 = 13.7

• 30 * 0.35 + 7 * 1.8 = 10.5 + 12.6 = 23.1

• 30 * 0.4 + 7 * 2.3 = 12 + 16.1 = 28.1

• 30 * 0.45 + 7 * 3.5 = 13.5 + 24.5 = 38

## Here is my Code:

``````def fareEstimator(ride_time, ride_distance, cost_per_minute, cost_per_mile):

for cpm, cpmile in zip(cost_per_minute, cost_per_mile):
result = round(( ride_time * cpm ) + ( ride_distance * cpmile ), 1)
print([result])

fareEstimator(30, 7, [0.2, 0.35, 0.4, 0.45], [1.1, 1.8, 2.3, 3.5])
``````

## Its output

``````[13.7]
[23.1]
[28.1]
[38.0]
``````

I've tried using List Comprehension where I am getting
`TypeError: 'float' object is not iterable`

## [13.7, 23.1, 28.1, 38]

Instead of printing, append to a list that you then return:

``````result = []
for cpm, cpmile in zip(cost_per_minute, cost_per_mile):
value = round(ride_time * cpm + ride_distance * cpmile, 1)
result.append(value)
return result
``````

This is easily converted to a list comprehension; just put the `result` expression at the front:

``````return [round(ride_time * cpm + ride_distance * cpmile, 1)
for cpm, cpmile in zip(cost_per_minute, cost_per_mile)]
``````

Demo:

``````>>> def fareEstimator(ride_time, ride_distance, cost_per_minute, cost_per_mile):
...     return [round(ride_time * cpm + ride_distance * cpmile, 1)
...             for cpm, cpmile in zip(cost_per_minute, cost_per_mile)]
...
>>> fareEstimator(30, 7, [0.2, 0.35, 0.4, 0.45], [1.1, 1.8, 2.3, 3.5])
[13.7, 23.1, 28.1, 38.0]
``````

Note that this returns the new list, if you still need to print this result, do so where you called `fareEstimator()`.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download