1

I have a little python program which print random HEX string, it generates one HEX string each time I run the program. i want the program to only generate a HEX string one's, that means the program should not generate a string that has already generated been generated.

EXAMPLE

python3 program.py

1. ab6b

2. 4c56

3. 1b13

4. ae8d

The next example show that the output is random and the program repeats lines.

1b13

ae8d

4c56

ae8d

My Code

import os
import binascii

print(binascii.hexlify(os.urandom(2)).decode('utf-8'))
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    Does this answer your question? [How do I create a list of random numbers without duplicates?](https://stackoverflow.com/questions/9755538/how-do-i-create-a-list-of-random-numbers-without-duplicates) – mkrieger1 Jun 12 '23 at 21:48

3 Answers3

5

We could store all previously generated strings and check any new string against this list, but you might run out of unique strings after a large number of runs.

import os
import binascii

generated_hexes = set()

while True:
    new_hex = binascii.hexlify(os.urandom(2)).decode('utf-8')
    if new_hex not in generated_hexes:
        print(new_hex)
        generated_hexes.add(new_hex)
Saxtheowl
  • 4,136
  • 5
  • 23
  • 32
1

For this situation, you need to store the codes in someplace, like a list in Python.

After this, is necessary to check if the new code exists in this list.

You can adapt the following code as you need.

import os
import binascii

list_codes = []

num = 1

while num == 1:
    hex = binascii.hexlify(os.urandom(2)).decode('utf-8')
    if hex not in list_codes:
      list_codes.append(hex)
      print(hex)
    num = int(input("Press 1 to continue "))
0

You need to save the values you print and before printing the next value, check if it's been printed before.

import os
import binascii

previously_printed = []
def print_new_random_hex():
    random_hex = binascii.hexlify(os.urandom(2)).decode('utf-8')
    while random_hex in previously_printed:
        random_hex = binascii.hexlify(os.urandom(2)).decode('utf-8')
    print(random_hex)
    previously_printed.append(random_hex)

In order to have the computer remember what was printed from a previous run, you need to have another file going which saves the values you print. In the code below, the file is previously_printed.txt

import os
import binascii

with open('previously_printed.txt', 'r') as file:
    previously_printed = file.read().split('\n')

with open('previously_printed.txt', 'a') as file:
    random_hex = binascii.hexlify(os.urandom(2)).decode('utf-8')
    while random_hex in previously_printed:
        print("yay we avoided printing", random_hex, "a second time!")
        random_hex = binascii.hexlify(os.urandom(2)).decode('utf-8')

    print(random_hex)
    file.write('\n' + random_hex)
Jacob Stuligross
  • 1,434
  • 5
  • 18