Create a set of numbers that are perfect cubes from 1 to 100


This Python code uses a set comprehension to create a new set named perfect_cubes, which contains perfect cube numbers from the range 1 to 100. Here's how the code works:

  • perfect_cubes = {x for x in range(1, 101) if int(x**(1/3))**3 == x}: This line initializes the set perfect_cubes using a set comprehension.
    • for x in range(1, 101): This part of the code sets up a loop that iterates through each number in the range from 1 to 100 (inclusive).
    • if int(x**(1/3))**3 == x: This part of the code filters the numbers to include only those that are perfect cubes. It checks if the cube root of x, converted to an integer, raised to the power of 3 is equal to x. If they are equal, it means that x is a perfect cube.
  • print(perfect_cubes): This line of code prints the perfect_cubes set to the console, containing perfect cube numbers.

Source Code

perfect_cubes = {x for x in range(1, 101) if int(x**(1/3))**3 == x}
print(perfect_cubes)

Output

{8, 1, 27}

Example Programs