pythonset

Reverse the elements of a set


I was trying to find a way to reverse the elements of a set. In the process of conversion we should not convert set into any other data type like list and we should not use recursions

Is their any way for it ?

Ex : S= {1,2,3}

Output:

3,2,1


Solution

  • I think this obeys your rules and prints the set in descending order:

    s = {1, 2, 3}
    for _ in range(len(s)):
        elem = max(s)
        s.remove(elem)
        print(elem, end=',' if s else '')
    
    # 3,2,1