Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop same letter appearing twice in list?

Tags:

python

im trying to write a progam where you enter either a vowel or a consonant 8 times and the list of letters you have chosen is then shown. Is there a way to program it so that the same letter cannot come up twice, e.g if you select vowel and get the letter a, then the letter a cannot be randomly chosen again? This is the program so far:

lt = 0
letters = []
while lt<8:
    letter = raw_input("Please enter v for a Vowel or c for a Consonant: ")
    if letter == "c":
        letters.append(random.choice(consonant)),
        lt = lt + 1
    elif letter == "v":
        letters.append(random.choice(vowel)),
        lt = lt + 1
    else:
        print("Please enter only v or c")

print ("letters:")
print letters
like image 338
Justin Avatar asked Dec 04 '22 01:12

Justin


1 Answers

Create a list of all consonnants and of all vowels, shuffle them randomly and then take one element at a time:

import random

con = list('bcdfghjklmnpqrstvwxyz') # in some languages "y" is a vowel
vow = list('aeiou')
random.shuffle(con)
random.shuffle(vow)
# con is now: ['p', 'c', 'j', 'b', 'q', 'm', 'r', 'n', 'y', 'w', 'f', 'x', 't', 'g', 'l', 'd', 'k', 'h', 'z', 'v', 's'] or similar
# vow is now: ['e', 'u', 'i', 'a', 'o'] or similar

letters = []
while len(letters) < 8:
    letter = raw_input("Please enter v for a Vowel or c for a Consonant: ")
    if letter == "c":
        if con:
            letters.append(con.pop())
        else:
            print("No more consonnants left")
    elif letter == "v":
        if vow:
            letters.append(vow.pop())
        else:
            print("No more vowels left")
    else:
        print("Please enter only v or c")
like image 191
eumiro Avatar answered Dec 24 '22 09:12

eumiro