Skip to main content

Section 3.2 Mini Project 2

For this mini project, you will be finding all perfect cubes of numbers in a list. You will then create a new list of only these perfect cubes. A perfect cube is a number that can be expressed as the cube of an integer. For example, 27 is a perfect cube because it can be expressed as 3^3 (3 * 3 * 3 = 27). On the other hand, 20 is not a perfect cube because there is no integer that can be cubed to get 20.

Checkpoint 3.2.1.

The list of numbers you will be working with is below. You can copy and paste this list into your code to get started.
numbers = [8, 81, 10, 27, 64, 15, 125, 7, 216, 5, 343, 12]
Remember that you will need to create a new list. Do that first. Afterwards, you will need to loop through each number if the list and check if it is a perfect cube. One way to check for a perfect cube is to check if the cube root of the number is an integer (whole number or zero). But, there are some weird things that go on with floating point numbers in python. If I ask if 4.999999 is an integer, python will say no, even though it is really close to 5. This could be because the answer really is 4.999999 or due to rounding errors.
So while there is a way to check if a float (remember: decimal) is really an integer, it is not always accurate. Instead, try taking the cube root, rounding it, and seeing if it cubed gives you back the original number. If it does, then the number is a perfect cube.
Solution.
The correct list of perfect cubes is [8, 27, 64, 125, 216, 343]. Here is one way to write the code to get that answer:
numbers = [8, 81, 10, 27, 64, 15, 125, 7, 216, 5, 343, 12]
perfectCubes = []  #create an empty list to store perfect cubes

for number in numbers:
    cubeRoot = round(number ** (1/3))  #calculate the cube root and round to whole number
    if cubeRoot**3 == number:  #check if the cubing gives you back the original number
        perfectCubes.append(number)  #if so, add the number to the perfectCubes list

print(perfectCubes)  #print the list of perfect cubes
This may seem like a round about way to get the perfect cubes, but it avoids the issues with floating point numbers in python. We will find ourselves working with the rounding errors of floating point numbers a lot, and we will see many different approaches to dealing with them.