PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

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

 July 20, 2022     integer, loops, python     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing