Word Generator - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Word Generator (/thread-5072.html) |
Word Generator - WordGenerator - Sep-17-2017 It works like this: 1 Vowel, 1 Consonant, 1 Vowel, 1 Consonant.. (So It sounds like a word..) VCVCVC Vowels: A, E, I, O, U Consonants: B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, X, Z / W, Y, Q.. This is what I got so far: import random import string VOWELS = list("AEIOU") CONSONANTS = list(set(string.ascii_uppercase) - set(VOWELS)) def generate_word(length = 5): return "".join(random.choice([VOWELS, CONSONANTS][_ % 2]) for _ in range(length)) print(generate_word(4))Now what's left is removing Q&Y&W out of consonants and make letters not repeat. Can somebody help me with this? RE: Word Generator - ichabod801 - Sep-17-2017 Since CONSONANTS is a list, you can remove the letters you want with the remove method ( CONSONANTS.remove('Q') ). To not double letters, I would turn the generator comprehension into a for loop that builds the string up character by character. Then have a while loop in the for loop, that picks random letters until it picks one that isn't the last character of the string so far.
RE: Word Generator - nilamo - Sep-21-2017 Quote:def generate_word(length = 5): return "".join(random.choice([VOWELS, CONSONANTS][_ % 2]) for _ in range(length)) Please, only use underscore for a variable name if you're not going to use that variable at all. [_ % 2] looks like some Perl nonsense, and shouldn't be anywhere in your code.
|