Python program: Frozenset of squares of odd numbers
10. Frozenset of Odd Squares
Write a Python program that generates a frozenset containing the squares of all odd numbers from 1 to 15 using set comprehension.
Sample Solution:
Code:
def main():
odd_numbers = {x**2 for x in range(1, 16) if x % 2 != 0}
frozenset_of_squares = frozenset(odd_numbers)
print("Frozenset of Squares of Odd Numbers:", frozenset_of_squares)
if __name__ == "__main__":
main()
Output:
Frozenset of Squares of Odd Numbers: frozenset({1, 121, 225, 9, 169, 81, 49, 25})
In the exercise above, we use a set comprehension to generate a set of squares of odd numbers from 1 to 15. The 'odd_numbers' set comprehension iterates through the range of numbers and filters out only the odd numbers using the condition x % 2 != 0. Based on the result of the set comprehension, we create a 'frozenset' named 'frozenset_of_squares'.
Finally, the program prints the 'frozenset' containing odd-numbered squares.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to generate a frozenset containing the squares of all odd numbers from 1 to 15 using set comprehension and then print the result.
- Write a Python function to create a frozenset of odd number squares within a specified range and then return the sum of the frozenset’s elements.
- Write a Python script to compute and display a frozenset of squares of odd numbers from 1 to 15, then compare it with a manually built set.
- Write a Python program to generate a frozenset of squared odd numbers, verify its immutability, and print its sorted list representation.
Python Code Editor :
Previous: Hashable composite keys using frozenset: Python code example.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.