CodeSignal put out a challenge by Uber that involves writing a "fare estimator" that involves a function dependent on cost per minute, cost per mile, ride time and ride distance.
The formula is along the lines of:
fare = (cost per minute) * (ride time) + (cost per mile) * (ride distance)
where ride time
and ride distance
are constant integers (or floats) and cost per minute
and cost per mile
are lists of integers and floats (as cost per minute and cost per mile depend on the car type).
This is my solution:
def fareEstimator(ride_time, ride_distance, cost_per_minute, cost_per_mile):
y, f = [], lambda w, x, y, z: (w * x) + (y * z)
for a, b in zip(cost_per_minute, cost_per_mile):
y.append(f(a, ride_time, b, ride_distance))
return y
I'm just looking for any kind of feedback on the code. Is there a better way to implement it? Can you recommend better coding styles? Is my algorithm good or is it a steaming pile of wank? Leave any feedback you want!
You can check out the full challenge here (but you might need to sign up): https://app.codesignal.com/company-challenges/uber/HNQwGHfKAoYsz9KX6
-
1\$\begingroup\$ Can you show how you expect the function to be called? In particular, it helps to know what types the arguments will be. \$\endgroup\$Toby Speight– Toby Speight2021年06月30日 19:40:26 +00:00Commented Jun 30, 2021 at 19:40
-
\$\begingroup\$ It's just called by an external code judge (I didn't implement a main function). \$\endgroup\$Aleksey– Aleksey2021年06月30日 23:13:35 +00:00Commented Jun 30, 2021 at 23:13
-
\$\begingroup\$ Ah, sorry, I see you have described the types of the arguments in the paragraph above the code. \$\endgroup\$Toby Speight– Toby Speight2021年07月01日 04:49:07 +00:00Commented Jul 1, 2021 at 4:49
1 Answer 1
Here are a few tips:
Unless it makes the code easier to read, avoid multiple assignments in one line. making your code shorter does not necessarily make it better, faster nor more maintainable.
Give better names to your variables
Use type hints
So, your code could be changed to this:
from typing import Iterable
def fareEstimator(ride_time: float, ride_distance: float, cost_per_minute_list: Iterable[float],
cost_per_mile_list: Iterable[float]) -> Iterable[float]:
result = []
def calculateFare(ride_time: float, ride_distance: float, cost_per_minute: float,
cost_per_mile: float) -> float:
return ride_time*cost_per_minute + ride_distance*cost_per_mile
for cost_per_minute, cost_per_mile in zip(cost_per_minute_list, cost_per_mile_list):
result.append(calculateFare(ride_time, ride_distance, cost_per_minute, cost_per_mile))
return result
Explore related questions
See similar questions with these tags.