Python program: Frozenset of squares of odd numbers
Python Frozenset Views Data Type: Exercise-10 with Solution
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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/extended-data-types/python-extended-data-types-index-frozenset-views-exercise-10.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics