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
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
Sets are not ordered. So, the sets {1, 2, 3}
and {3, 2, 1}
are essentially the same.
You must use lists if you want ordered elements.
list1 = [1, 2, 3]
list2 = list1[::-1]
print(list2)
Output is
>>> [3, 2, 1]
EDIT: If you want to use for loop:
list1 = [1, 2, 3]
list2 = []
for x in range(len(list1)-1, -1, -1):
list2.append(list1[x])
print(list2)
The logic of this code is:
The range(a, b, c)
function takes 3 arguments : from a
to (b-1)
with each step of c
.
So, we move from the last element (len(list1)-1) of the list1
upto the first element -1 with a step of -1, so that it decreases with each step.
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