I want to implement a random word generator that would not use Import statements. The solution is working for a *nix system. The solution does yield a random word, but please suggest:
- How to make the function optimally/safely return words with a higher position in the list(e.g. now we're almost guaranteed to return an 'A' word)
- How to get a word with min/max length instead of length
- Should I break this into smaller functions?
- How to make the code more readable/higher performance
- Is there a better approach to this problem? How to tell which modules are better off imported instead of implemented from scratch(except for the built-ins)?
def generate_random_word(length=8):
"""
Return a random string from /usr/share/dict/words on a *nix system
"""
with open('/usr/share/dict/words', 'r') as words_file, open("/dev/random", 'rb') as random_file:
random_words = words_file.read().split('\n')
size_words = [x for x in random_words if len(x) == length]
for _ in range(0, 100):
while True:
try:
random_word = size_words[(int.from_bytes(random_file.read(1), 'big'))]
except IndexError:
continue
break
return random_word