2

I am looking to generate a random word list from a set of characters in python. Problem here:-

It is Generating like:- aaaaaa aaaaab aaaaac ...... So on

I want to add random function so it generate same length with randomization of alphabets it has like:- a15bef f45acd 9bbac0 ...... So on

Look With same length but random.

How to add random function to it?

#Code
import itertools

chrs = 'abcdef0123456789' # Change your required characters here
n = 6 # Change your word length here

for xs in itertools.product(chrs, repeat=n):
   print(''.join(xs))

please help me to solve it.

3

4 Answers 4

3

itertools.product will generate all the possible values. Instead, what you want is to pick n random characters from chrs and concatenate them:

import random

chrs = 'abcdef0123456789' # Change your required characters here
n = 6 # Change your word length here

print(''.join(random.choices(chrs, k=5)))
Sign up to request clarification or add additional context in comments.

1 Comment

Very good suggested and its working without itertools and consume less memory means faster work.
1

You can do it by random.choice:

import random
chrs = 'abcdef0123456789'
n = 6
result = ''.join(random.choice(chrs) for _ in range(n))

Comments

0
''.join(random.choice(‘abcdef0123456789’) for _ in range(N))

A cryptographical more secure option is here, below example will generate random string using all undercase alphabets and digits

''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))

2 Comments

it says - NameError: name 'string' is not defined
We import string, a module that contains sequences of common ASCII characters, and random, a module that deals with random generation
0

I use something like this

import random
def generateAWord (length):
    i = 0
    result = ""
    while i < length:
        letter = chr(33 + int(93 * random.random()))
        result += letter
        i +=1
    return result

33 in inside chr is the first ascii decimal that you want( 33 represent {!}). random.random() return the next random floating point number in the range [0.0, 1.0] so it times that 0.0 - 1.0 by 93 for example 0.1732*93 will result 16,1076 (and it cast that to int, so it will end as 16). So 93 represent the max result from the starting ascii decimal that you want(in this case 33) until the max ascii decimal that you want(in this case 33+93 is 126 which is {~} in ascii decimal).

Then chr will convert that result to char.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.