Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I wrote a little code but something might be wrong

The goal of this code is to generate a little list of 6 random numbers from 1 to 60, erase any repeated item and sort it, but I think something may be wrong because sometimes I execute this code and nothing happens, probably when a repeated number is drawn.

This is one of my first codes, so I’m thankful for any pointers.

import random

a = []

while len(a) < 6 or len(a) != len(set(a)):
    a.append(random.randint(1, 60))

if len(a) > 6:
    a = set(a)

a.sort()

print(a)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You correctly identified the issue. The problem is indeed when a repeated number is chosen.

Once you generate a random number, you never delete it. So once a repeated number happens to be added to a, len(a) never equals len(set(a)), as set(a) will always be at least one element shorter, no matter how many numbers you add to it. This means your while loop will never terminate.

The solution to this is to realise that you don’t care about the length of a, only about the length of set(a), since you don’t care how many numbers are added to a before you get 6 unique ones. So, all you need to check as the condition for you while loop is len(set(a)) < 6. Note that this allows you to remove the check right after the while loop. Finally, note that sets are unordered, and a.sort() will raise an error. If you really want it sorted, call the sorted function on it. Hope this helps!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading