2

I am currently working on a flask app for school where I have to generate a random unique set of numbers.

My current code is this:

amount_of_positions = 6
amount_of_numbers = 6
number_set = set() 
while len(number_set) < amount_of_positions:
    rnd = random.randrange(1, amount_of_numbers + 1)
    number_set.add(rnd)

The rnd variable is generating correct random numbers. But when I add that number in the set it gets placed in order instead of at the end of the set.

The result of the above code is: {1, 2, 3, 4, 5, 6}

I can't figure out why it keeps ordering the numbers. Can anyone help me?

BlueDragon709
  • 196
  • 1
  • 12
  • This is an excellent question and i look forward to answers on it. sets are unordered but running your code I can see it adding the numbers in various orders yet printing the set the numbers are in order. I am not sure if set like dict will just decide the ordering for you instead of mainting a positional index like liist or tuple does – Chris Doyle Mar 03 '20 at 13:54
  • I did read this https://stackoverflow.com/a/8084831/1212401 which suggest the sets will be ordreed a bit like python dict keys get ordered in earlier versions, where it will create a hash and store it appropriatly. You can see the value of the set becomes unordered if you change your amount_of_numbers to something like 10k. so it might be a special case of caching or hashing small ints in relative order. This still doesnt answer the why your set is ordered in your case but does confirm sets with ints are not assured to be in order – Chris Doyle Mar 03 '20 at 13:55
  • What's `amount_of_numbers`? – Kelly Bundy Mar 03 '20 at 13:58
  • It is also 6 in this case – BlueDragon709 Mar 03 '20 at 13:59
  • 2
    You souldn't be using sets when you care about the order, that's not their purpose and you can't rely on their order. I don't see how the elements being ordered is a problem in your example, but if it is (meaning the order matters) don't use a set. Good question though. – chuck Mar 03 '20 at 13:59
  • @HeapOverflow I replicated the issue by adding `amount_of_numbers=10`, i then replicated the unordered with setting this is 10000 – Chris Doyle Mar 03 '20 at 13:59
  • 3
    FWIW, you can shorten this entire code to `number_set = random.sample(range(1, amount_of_numbers + 1), amount_of_positions)`… – deceze Mar 03 '20 at 14:03
  • I thought that a set was a handy thing that forces unique values and when adding stuff it would put it at the end. But now that I know that set isn't following any order I am going to try something else @chuck2002 – BlueDragon709 Mar 03 '20 at 14:03
  • @BlueDragon709 which version of python are you using? – Chris Doyle Mar 03 '20 at 14:06
  • Python version 3.8.2 – BlueDragon709 Mar 03 '20 at 14:07
  • With `amount_of_positions = 6`, you'd need `amount_of_numbers` to be 32 or larger in order to see any unorderedness. – Kelly Bundy Mar 03 '20 at 14:13

0 Answers0