From 7cc9205fbf8849b7a190d9e537177f325e8a28a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gon=C3=A7alo=20S=2E=20Martins?= Date: Tue, 17 May 2016 21:46:07 +0100 Subject: [PATCH] Fix a potential infinite loop. If the word file has fewer words than the number we're looking for, we use'em all. --- crossword_generator.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/crossword_generator.py b/crossword_generator.py index 3a24ad8..5e83d7c 100755 --- a/crossword_generator.py +++ b/crossword_generator.py @@ -42,13 +42,17 @@ def read_word_list(filename, n_words=100): for line in words_file: words.append(line.strip()) - # Select n_words words - while len(selected_words) < n_words: - # Choose candidate randomly - candidate = words[random.randint(0, len(words)-1)] - # Append candidate if it's not already there - if candidate not in selected_words: - selected_words.append(candidate) + # If we have few words, we use them all + if len(words) <= n_words: + selected_words = words + # If we have enough words, we have to select + else: + while len(selected_words) < n_words: + # Choose candidate randomly + candidate = words[random.randint(0, len(words)-1)] + # Append candidate if it's not already there + if candidate not in selected_words: + selected_words.append(candidate) # ... and return the list return selected_words