Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Word Generator
#1
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?
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Problem: Check if a list contains a word and then continue with the next word Mangono 2 2,495 Aug-12-2021, 04:25 PM
Last Post: palladium
  Python Speech recognition, word by word AceScottie 6 15,999 Apr-12-2020, 09:50 AM
Last Post: vinayakdhage
  print a word after specific word search evilcode1 8 4,831 Oct-22-2019, 08:08 AM
Last Post: newbieAuggie2019
  difference between word: and word[:] in for loop zowhair 2 3,671 Mar-03-2018, 07:24 AM
Last Post: zowhair
  receive from a generator, send to a generator Skaperen 9 5,504 Feb-05-2018, 06:26 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020