Created
April 29, 2023 14:15
-
-
Save kchromik/3b0ad185e9d16af3f7a0516c32f33232 to your computer and use it in GitHub Desktop.
Coding Challenge Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
class RandomWordGenerator: | |
def __init__(self): | |
self.graph = {} | |
self.first_letters = set() | |
self.last_letters = set() | |
def insert(self, words): | |
for word in words: | |
if not word: | |
return | |
self.first_letters.add(word[0]) | |
self.last_letters.add(word[-1]) | |
for index, current_char in enumerate(word): | |
next_char = word[index + 1] if index < len(word) - 1 else None | |
if current_char not in self.graph: | |
self.graph[current_char] = set() | |
if next_char is not None: | |
self.graph[current_char].add(next_char) | |
def generate_random_word(self): | |
if not self.first_letters: | |
return "" | |
current_letter = random.choice(list(self.first_letters)) | |
random_word = [] | |
while True: | |
random_word.append(current_letter) | |
if current_letter in self.graph: | |
next_letter = random.choice(list(self.graph[current_letter])) | |
if next_letter in self.last_letters and random.choice([True, False]): | |
random_word.append(next_letter) | |
return "".join(random_word) | |
else: | |
current_letter = next_letter | |
else: | |
return "".join(random_word) | |
words = ["apple", "banana", "cabbage"] | |
generator = RandomWordGenerator() | |
generator.insert(words) | |
random_word = generator.generate_random_word() | |
print(random_word) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment