Friday, 6 June 2025

Python Coding challenge - Day 532| What is the output of the following Python Code?

 


Code Explanation:

Function Definition
def unique_sums(nums):
Defines a function named unique_sums that takes a list nums as input.

Initialize a Set to Store Unique Pairs
    seen = set()
Creates an empty set called seen.
This set will store unique unordered pairs using frozenset, which ensures that the order of numbers doesn't matter (i.e., {1, 2} is the same as {2, 1}).

Outer Loop – Iterate Over First Element of the Pair
    for i in range(len(nums)):
Loops through each index i of the list nums.

Inner Loop – Iterate Over Second Element of the Pair
        for j in range(i + 1, len(nums)):
Loops through each index j such that j > i, forming all unique pairs without repetition.
This avoids comparing the same pair twice or comparing an element with itself (e.g., avoids both (1, 2) and (2, 1) or (2, 2)).

Store the Unordered Pair as a frozenset
            seen.add(frozenset([nums[i], nums[j]]))
Forms a pair using nums[i] and nums[j].
Converts the pair into a frozenset, making the pair unordered and hashable.
Adds the frozenset to the seen set.
If the pair already exists in seen, it won't be added again (ensures uniqueness).

Return the Count of Unique Pairs
    return len(seen)
Returns the number of unique unordered pairs collected in the seen set.
Example Call
print(unique_sums([1, 2, 3, 2]))
Calls the function with the list [1, 2, 3, 2].
Pairs formed and stored:
Pair frozenset Already in seen?
1,2 frozenset({1,2}) No
1,3 frozenset({1,3}) No
1,2 frozenset({1,2}) Yes
2,3 frozenset({2,3}) No
2,2 frozenset({2})         No
3,2 frozenset({2,3}) Yes

Final seen set:
{frozenset({1,2}), frozenset({1,3}), frozenset({2,3}), frozenset({2})}

Output:
4

Download Book - 500 Days Python Coding Challenges with Explanation


0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (152) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (251) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (298) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (217) Data Strucures (13) Deep Learning (68) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (47) Git (6) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (186) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (11) PHP (20) Projects (32) Python (1218) Python Coding Challenge (884) Python Quiz (342) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)