I wrote a little code but something might be wrong

Question:

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)
Asked By: Kaiky

||

Answers:

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!

Answered By: Morgoth Bauglir
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.