Question 02: Least Distance to Travel
Date: 2022-06-18
Language: Python
Code Link: Github
Background
Had a technical interview for a IT role and they asked the question below to see how a person would work through and solve the problemKey items they were looking for:
- Ask questions about the problem and seek help for any clarity required
- Talk through with them how the problem is being solved while solving it
- At the end, explain how the problem was solved
- How efficient the solution code was and the Nth value required
- Communication skills
- Coding methodology and process. Whether it follows good practice or just ad-hoc style
Problem
There is a group of N friends represented by a list of dictionaries, where a dictionary is of the form:{“name”: “David”, “location”: (x,y,z)}The friends want to host a party but want the friend with the optimal location (least distance to travel as a group) to host it (least distance to travel as a group) to host it. Write a function to return the friend that should host the party.
Data:
friends = [{"name": "Bob", "location": (5, 2, 10)}, {"name": "David", "location": (2, 3, 5)}, {"name": "Mary", "location": (19, 3, 4)}, {"name": "Skyler", "location": (3, 5, 1)}]
Solution
This was the initial solution below which is not good at all and what you should avoid. However, under time pressure it is important to stay cool and take things slowly. In the end if you are qualified you can succeed.Possible Answer
def do_calc(x, friends: pd.DataFrame({})): total_distance = 0 for _row in friends.iterrows(): distance = math.dist(_row[1]['location'], x) total_distance += distance return total_distance friends_pd = pd.DataFrame(friends) friends_pd['total_distance'] = friends_pd['location'].apply(lambda x: do_calc(x, friends_pd)) friend_min_dist = friends_pd[friends_pd['total_distance'] == friends_pd['total_distance'].min()] print(f'Friend with minimum distance: {friend_min_dist.loc[:, "name"].values[0]}, distance: {friend_min_dist.loc[:, "total_distance"].values[0]}')