I need to create a list of random characters that are generated from random numbers. One list needs to be the letters generated from the random numbers, while the other list will get letters that are already in the first list. I have seen the import string method that uses the ascii, but I dont fully understand that. So far I have used the import random method and have been able to generate the random numbers but I feel my code is too long and that there should be an easier way.
Each time a random number is generated the program should convert it to a letter and add to a list (called
uniqueList) only if the number is not already present in the list. Stop adding the numbers once the list
contains 15 characters.
here is a sample of the code I have so far:
uniqueList = 
excludedList = 
count = 0
randomNumber = random.randint(*random.choice([(65,90), (97,122)]))
if(randomNumber == 65):
letter = 'A'
if(randomNumber == 66):
letter = 'B'
if(randomNumber == 67):
letter = 'C'
if(randomNumber == 68):
letter = 'D'
if(randomNumber == 69):
letter = 'E'
if(randomNumber == 70):
If you just need a random
letter, you can simplify the logic by using
import string import random my_char = string.letters random.choice(my_char) # returns 'z'
string.letters will return string of all letters i.e.
Below is the modified code based on your logic of code (using
random.choice() with random number) as:
import string import random my_char = string.letters # Value returned by string.letters: # 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' randomNumber = random.randint(*random.choice([(65,90), (97,122)])) if randomNumber >=65 and randomNumber <=90: print my_char[randomNumber-65] elif randomNumber >=97 and randomNumber <=122: print my_char[randomNumber-97+26]