Day 5 In-class Assignment: Practicing with functions (for profit!)#

✅ Put your name here.#

✅ Put your group member names here.

As we’ve mentioned previously, writing functions in Python can be very useful. In this assignment, you’ll spend some more time writing functions so that it starts to become second nature. If you get into the habit of writing functions early on, you’ll find that you start writing more efficient code as the problems you’re trying to solve get more complicated!

In this assignment, we’ll use functions to compute distances and optimize rideshare routes.

Learning Goals:#

By the end of this assignment you should be able to:

  • Confidently write and execute functions in Python using varying numbers of input parameters, default parameters, and returned values


1. Revisiting the last function from the pre-class assignment#

In your pre-class assignment, you were asked to do the following:

  1. Write a function called x_squared.

  2. The function should take in a list of \(x\)-values of any length, but should have a default of [1,2,3].

  3. The function should return a new list of values that are \(x^2\) values of the original input values.

  4. Print the resulting new list.

Hopefully you were able to figure this out, but if not here’s one possible solution:

def x_squared(x_values=[1,2,3]):
    x_sq = []
    for x in x_values:
        x_sq.append(x**2)
    return x_sq

x2 = x_squared()
print(x2)

Notice that when the function is called, it doesn’t take any input and yet produces an output. This is the upside to defining a default value for the input. Of course, I can also make the \(x\)-values to be anything I want. Like so:

x = [3, -5, 10, -6, -7, 2]
x2 = x_squared(x)
print(x2)

Making this function more flexible#

Now, the above function is great for computing \(x^2\), but what if I wanted a function that could more generally compute the values for a list of \(x\)-values raised to any power?

As a group, design a small function called compute_exponent that satisfies the following:

  1. Given a list of \(x\)-values, it computes the value of \(x^a\) for each value, where \(a\) is a parameter that is fed into your function.

  2. The default value of \(a\) is “2”.

  3. It returns the list of all the \(x^a\) values.

Make sure you print out the list of resulting values to confirm that your code is working. Run your function for a variety of input values.

# WRITE PSEUDO-CODE HERE (in the form of comments)
# Put your code here

✅  Question: What happens in your function if \(a=0.5\) and your \(x\)-values are a combination of positive and negative numbers?

Put your answer here

✅  Question: What if you only wanted your function to return a list of new values if all of the values are non-imaginary numbers? Explain how you might re-write your code to accomplish this. You should brainstorms ideas with your group!

In case you don’t remember what imaginary numbers are: https://en.wikipedia.org/wiki/Imaginary_number

Put your answer here


2. Computing distances with functions#

Anything look familiar about this map?


For the next part of this assignment, we’re going to think about how we might be able to write functions that can be used to compute distances on a map.

2.1 Computing the Euclidean distance#

“Euclidean distance” is simply the distance of the straight line that connects two points in Euclidean space. It’s basically the distance “as the crow flies”. On a map, it might look something like this:

For this part of the assignment, write a function that takes in two points on an \(x\)-\(y\) plane and returns the Euclidean distance between these two points. Define your function so that by default, the “stop” point is the point (0,0). Don’t worry about the units of this distance for this problem.

Work with your group to figure this out!

# Put your function here

2.2 Computing the “Lyft” distance#

For this part of the assignment, let’s say that you’ve been thinking about starting a new rideshare company similar to Uber or Lyft. You’ve started thinking about how you should go about estimating the amount you should charge for a given ride, but you’ve realized that computing the Euclidean distance between two points doesn’t really make sense. Now you need to create a new function that computes an estimate for the total distance of the ride for your new “Lyft-like” service.

When you’re driving a car you can’t just travel in a straight line between two points, you’re forced to drive along the grid structure defined by where the streets are. Your path might look something like this:

Another potentially familiar place…


For the purposes of computing these new “Lyft”-like distances, you’re going to assume that the drivers for your company are generally pretty good about taking the shortest possible route, and you’re also going to assume that, most of the time, the streets will have a pretty standard grid-like structure. After all, it would be pretty hard to predict just how irregular the routes might end up being.

Write a function for computing a “Lyft” distance based on the restriction that the car must travel on a grid of roads that run parallel to the \(x\) and \(y\) axes of an \(x\)-\(y\) plane. Your function should take a starting point and a stopping point as input variables and return the distance estimate. Your estimate will essentially tell you how many blocks the driver will travel to get to the destination. Use the white boards to plan out how to do this calculation! Hint: you may want to use the absolute value function for this calculation.

# Put your function here

2.3 Creating a fare-computing function#

Let’s assume that you want to be able to quickly calculate an estimate for the cost of the trip so that you can let your riders know roughly how much you’ll charge them. To start with, you’re going to use a flat rate of 40 cents per unit distance the driver travels.

Write another function called trip_cost that uses the function you just wrote for computing the total distance of the ride to print the cost of the trip so that it reads “The cost of the trip will be $< amount >” where < amount > is the total in dollars that the trip will cost. Your function should take the starting point, the stopping point, and the rate (with a default value) as inputs.

# Put your function here

3. Combining your functions#

Now that you’ve written two different functions for finding the distance, you’re thinking that it would be more convenient if you could use the same function to compute both the Euclidean distance and the Lyft distance. It would also make it a lot easier to compare how much longer the Lyft distance is than the Euclidean distance.

Write a function that is capable of computing the Euclidean distance or the Lyft distance based on a keyword argument call path_type.

  • If the path_type is ‘Lyft’, compute the Lyft distance, otherwise compute the standard Euclidean distance.

  • Make sure that the default stopping point is (0,0).

As before, your function should return the distance.

# Put your code here

Write another function that uses your previous function to compute both the Euclidean distance and the Lyft distances and prints:

“The Lyft distance is < X > times longer than the Euclidean distance”

where < X > is the appropriate ratio of the two distances.

Compare the two distances for a starting point of (-2, -6) and stopping point of (4,5).

# Put your code here

4. Planning your route#

Now that you’ve worked out a system for estimating travel distances and ride fares, you’re ready to start testing your new rideshare service. You fire up your fancy new program and immediately get three simultaneous rider requests, but luckily they all are looking for a ride to the same place – the airport!

You plan on picking up all three passengers on the same trip so that you can drop them all off at the same time. You want to take the shortest possible route so that you minimize the cost of gas and, in turn, the amount of money the trip costs you!

The challenge: You need to create a function that takes in a starting position, a list of three rider locations, and a stopping location and determines the order of rider pickups that will require the least amount of driving. You want to make the default stopping location be the airport, since you figure this is where people will be headed most often. You should be able to use your function for computing the Lyft distance to help solve this problem.

Work out a plan for your function on a whiteboard or piece of paper first! You may need to draw a diagram to figure out how to solve this.#

Once you’ve come up with a plan, try writing the function. The function should return the list of rider locations in the appropriate pick-up order and the total distance of the trip.

Let’s assume that:

  1. Your starting location is (-2,3).

  2. The ride locations are (-1, -2), (3,3), and (2, -1).

  3. The stopping location, the airport, is at (4,0).

# Put your code here

Time permitting:#

If you finish this assignment early, take a moment to go back to the end of Part 1 and try to code up your solution for dealing with imaginary numbers in your compute_exponent function.


An aside, for those that are interested#

The maps in this assignment were made, in part, using the OSMnx Python package. You can check out some example code here.


Congratulations, you’re done!#

Submit this assignment by uploading it to the course Desire2Learn web page. Go to the “In-class assignments” folder, find the dropbox link for Day 5, and upload it there.

See you next class!

© Copyright 2024, Michigan State University Board of Trustees