Home > Enterprise >  Generate Random Character's
Generate Random Character's

Time:10-30

Generate N * N Random character .

I will make code perfect but it's not working .

pls any one help men.

import random

n=int(input("Enter a number :"))

matrix = []

for i in range(n):
    for j in range(n):
        temp = chr(random.randrange(33,126))
        if temp in matrix:
            j-=1
        else:
            matrix.append(temp)
        
print(matrix,len(matrix))

n = 4 I want 16 random character.

n = 5 ['a' , '@' , '5' ......] upto 25 characters I want.

CodePudding user response:

import random

n = int(input("Enter a Number: "))

random_nums = [random.randint(33,127) for i in range(n*n)] 
matrix = [chr(i) for i in random_nums]

print(matrix, len(matrix))

CodePudding user response:

Simply use random.sample

import random
choices = "".join(chr(i) for i in range(33, 127))
k = 6
print([random.sample(choices, (k**2)%(len(choices)-1)) for i in range(0, k**2, len(choices))][0])
 # output : ['d', 'H', 'u', 'g', '2', 'j', 'z', '0', '#', 'x', '4', 'h', '`', '{', 'r', '5', 'V', 'A', '=', '"', 'f', 'n', 'p', ',', 'k', 'o', '*', ' ', '3', 'S', 'U', '_', 's', 'Y', 'y', 'P']

CodePudding user response:

I think you're trying to build an N * N matrix. If so then:

from random import choices as CHOICES

CHARS = [chr(i) for i in range(33, 127)]

N = int(input('Input N: '))

matrix = [CHOICES(CHARS, k=N) for _ in range(N)]

print(matrix)

Possible output:

[['N', '%', ' ', 'u'], ['_', '8', 'T', '.'], ['8', '1', '=', 'O'], ['8', 'G', 'T', 'I']]
  • Related