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
.png)

0 Comments:
Post a Comment