Generate a set of positive square roots from a set of positive numbers
This Python code uses a set comprehension to create a set named positive_sqrt that contains the square roots of the numbers in the set positive_numbers. Here's how the code works:
- positive_numbers = {1, 4, 9, 16, 25}: This line initializes a set named positive_numbers containing five positive integers.
- positive_sqrt = {math.sqrt(x) for x in positive_numbers}: This line initializes the set positive_sqrt using a set comprehension.
- for x in positive_numbers: This part of the code sets up a loop that iterates through each number in the positive_numbers set.
- {math.sqrt(x)}: For each number, this part includes its square root, calculated using the math.sqrt() function, in the positive_sqrt set.
- print(positive_numbers): This line of code prints the original positive_numbers set to the console.
- print(positive_sqrt): This line of code prints the positive_sqrt set to the console.
Source Code
import math
positive_numbers = {1, 4, 9, 16, 25}
positive_sqrt = {math.sqrt(x) for x in positive_numbers}
print(positive_numbers)
print(positive_sqrt)
Output
{16, 1, 4, 9, 25}
{1.0, 2.0, 3.0, 4.0, 5.0}