-4

I want to generate 10 unique English letters and append them to a list in Python.

This is what I tried:

for i in range(10):
    rand = random.choice(string.ascii_letters)
    print(rand)
khelwood
  • 55,782
  • 14
  • 81
  • 108

4 Answers4

0
import numpy as np
n = 10

letterlist = [chr(i) for i in np.random.randint(ord('a'), ord('z') + 1, n)]
print (letterlist)
Panda
  • 91
  • 1
  • 12
0

You need to import both random and string libraries. And use a variable of type 'list'

import random
import string 

ls=[]

for i in range(10):
    rand = random.choice(string.ascii_letters)
    ls.append(rand)
    
print(ls)

This is what the code will look like..

projjal
  • 264
  • 3
  • 10
0

There are so many good ways to do this, and I believe people are downvoting your question due to the lack of explanation as to why your method fails. I also see a lot of imports and libraries, but this is such a simple question that it can be answered in a very vanilla fashion, just import random.

import random

##define the list to keep valid letters in
letters = []
##add all letters between A and Z, capital, +1 because range isn't end inclusive
for i in range(ord('A'),ord('Z')+1):
    letters.append(chr(i))
##same but for lowercase letters
for i in range(ord('a'),ord('z')+1):
    letters.append(chr(i))

##returns a random string of n characters
def n_string(n):
    result = ""
    for i in range(0,n):
        ##picks a random spot in the letters list, randrange IS end inclusive
        spot = random.randrange(0,len(letters)-1)
        result += letters[spot]
    return result

print(n_string(10))

That's just one way to do it, see if you can think of any ways to optimize it or do it differently.

(Just a hint, try skipping the letters generation and just creating a number between ASCII A (65) and ASCII A + 52 (the count of all lower and uppercase letter). If that number is greater than 90 (Z), add something to it to make it the lowercase letter.)

Aaron
  • 132
  • 10
0

This can be also the answer:

import random
import string

ls = []
while len(ls) !=10:
    rand = random.choice(string.ascii_letters)
    rand =rand.lower()
    if rand not in ls:
        ls.append(rand)

As this does get repeated alphabets. This code gets a random Unique 10 letters