ArthurIsNo
ArthurIsNo

Reputation: 11

How to make strings not repeat in a random word generator

I am making a random string generator, however I am having issues making the strings not repeat when generating

Here's the Code:

import random
import string

repeat = True

pp = input("What's your text? ").lower()
pl = len(pp)

while repeat == True:
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(pl))
    print(result_str)
    if result_str == pp:
        repeat = False

How can I make the strings always different from one another

I've tried searching it up on google, but got no result I was happy with.

Upvotes: 1

Views: 156

Answers (1)

I'mahdi
I'mahdi

Reputation: 24059

You can try like below. In the below example, I suppose you want the length of each string==10 and you want to generate 10 strings that don't have repeating. In each iteration, we generate a random string and if generated string doesn't exist in seen we add generate string to seen and increase one-time cnt. Until cnt < count_not_repeated_string we continue to generate random strings.

import random
import string


pl = 10
count_not_repeated_string = 10
cnt = 0
seen = set()

while cnt < count_not_repeated_string:
    letters = string.ascii_lowercase
    result_str = ''.join(random.choice(letters) for i in range(pl))
    if not result_str in seen:
        seen.add(result_str)
        cnt += 1
print(seen)

Output:

{'pmyolioqqh', 'lufictzhov', 'jifdiwvupa', 'eafmoxmiqx', 'ktdfmekwoa', 'vtpjtittgt', 'rvvfdreuox', 'crfgbveazn', 'jntmlfhixy', 'gkhxcfuydy'}

Upvotes: 1

Related Questions