I was wondering how to generate a random 4 digit number that has no duplicates in python 3.6 I could generate 0000-9999 but that would give me a number with a duplicate like 3445, Anyone have any ideas thanks in advance
Asked
Active
Viewed 782 times
1
-
Also related: https://stackoverflow.com/questions/9690009/pick-n-items-at-random-from-sequence-of-unknown-length – Aran-Fey Apr 29 '18 at 21:08
1 Answers
-1
- Generate a random number
- check if there are any duplicates, if so go back to 1
- you have a number with no duplicates
OR
Generate it one digit at a time from a list, removing the digit from the list at each iteration.
- Generate a list with numbers 0 to 9 in it.
- Create two variables, the result holding value 0, and multiplier holding 1.
- Remove a random element from the list, multiply it by the multiplier variable, add it to the result.
- multiply the multiplier by 10
- go to step 3 and repeat for the next digit (up to the desired digits)
- you now have a random number with no repeats.

Jeffrey Phillips Freeman
- 897
- 1
- 9
- 28
-
-
@CalebHope treat it as a string and use regex on it, or do modulus 10 to get the last digit, store in a set, then divide by 10 and do modulus 10 to get the next digit, also store in a set. Then when your done check if the set is the same size as the original number of digits. If it is smaller there were repeats. – Jeffrey Phillips Freeman Apr 29 '18 at 21:14
-
@CalebHope Easier yet sinc ea string is treated as a list you can just treat the number like a string and stick it right into a set, then compare the set length and the string length. No math needed. – Jeffrey Phillips Freeman Apr 29 '18 at 21:17
-
Thanks a lot i ended up with this RdmArray = ["0","1","2","3","4","5","6","7","8","9"] RdmArray = random.sample(RdmArray, 4) RdmNum = "".join(RdmArray) – Caleb Hope Apr 29 '18 at 21:38
-
@CalebHope yup that should work. Accept this answer if you feel it answered this for you (or not if it didnt). Helps us out :) Its the little grey check mark next to the voting controls. – Jeffrey Phillips Freeman Apr 29 '18 at 21:46