0

If I generate a random string (alphanumeric with alphabets in capital) in Python, how do I ensure that the whole string is not repeated again? Below is my code for randomly generating a string of 6 characters. If a string, say "GU8YZ9" is generated, how do I ensure that "GU8YZ9" is not generated again? Is there any algorithm or in-built function for that?

import random, string

num = 6

chars = string.ascii_uppercase + string.digits
''.join(random.choice(chars) for x in range(num))
Sam Mason
  • 15,216
  • 1
  • 41
  • 60
Arya
  • 54
  • 8
  • 2
    The only way to ensure that your random string is not repeated again is to store a `set` of all previous random strings, and check that every time you make a new one to make sure it's not in there. If you need _absolutely 100% unique_ alphanumeric strings, have you considered using [`uuid`](https://docs.python.org/3/library/uuid.html)s, which are encoded in such a way as to be both partially random and almost perfectly unique? – Green Cloak Guy Oct 22 '20 at 04:05
  • Okay, I will try that out! Thanks! If anyone has got any other solution, please help! – Arya Oct 22 '20 at 04:08

2 Answers2

0

Create a set with all the already generated ones.

import random, string

s = {''}

num = 6
chars = string.ascii_uppercase + string.digits

chosen = ''
while chosen not in s:
    chosen = random.choice(chars, k = num)
    if len(s) == len(chars) ** num:
        print(f'There are no other possible combination of {chars} into {num} str')
        chosen = ''
        break

print(chosen)

I have just saw @green-cloak-guy comment, so I though I should also point to his comment.

You can also use itertool's product and iterate over it (not efficient and deterministic), like:

import string
from itertools import product 

num = 6
chars = string.ascii_uppercase + string.digits

for n in product(*[chars] * num):
    print(''.join(n)) # unique from chars ** num possibilities
Felipe Whitaker
  • 470
  • 3
  • 9
  • Okay thank you so much! More solutions are welcome! – Arya Oct 22 '20 at 06:07
  • For any solution you will need a way to generate the string and a method to check if it was already generated. The first solution tries to generate a new one and check if it was already generated (thus starts fast, but might take a long time when there aren't many possibilities left). The second one will generate everything upfront (which will take *a lot* of memory) and then iterates over them. You might want to check [this](https://stackoverflow.com/questions/26030811/generate-a-unique-string-in-python-django) for better methods. – Felipe Whitaker Oct 22 '20 at 06:18
  • You should've probably accepted an answer that answers your question – Felipe Whitaker Oct 22 '20 at 14:46
-1

Generate string -> Store String in ArrayList or any other Data Structure -> Use if statement to check whether or not the generated number is duplicated -> Generate a different string if it is a duplicate.->