Wednesday, July 20, 2022

[FIXED] How to iterate over a set of unequal integers in order?

Issue

In the following example, the How to iterate over a list of integers?

index_set = {2, 4, 5*5, 10*5, 15*5, 20*5, 30*5, 40*5, 45*5}
for index in index_set:
      ...
      print(index, end=',')
      ...

Output

225,2,4,100,200,75,50,150,25,

Desired output

2,4,25,50,75,100,150,200,225

Some answers change the question to how to print a set of numbers in order and remove the loop. There is additional processing besides the display of the integer in the loop.

I believe the simplest answer is to change from a set to a list so order is kept.


Solution

No need for the loop:

index_set = {2, 4, 5*5, 10*5, 15*5, 20*5, 30*5, 40*5, 45*5}
index_set = ", ".join([str(i) for i in sorted(index_set)])
print(index_set)

Output:

2, 4, 25, 50, 75, 100, 150, 200, 225


Answered By - Eli Harold
Answer Checked By - Gilberto Lyons (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.