Practice Python

Beginner Python exercises

15 October 2016

Pick Word Solutions

Exercise 30

This exercise is Part 1 of 3 of the Hangman exercise series. The other exercises are: Part 2 and Part 3.

In this exercise, the task is to write a function that picks a random word from a list of words from the SOWPODS dictionary. Download this file and save it in the same directory as your Python code. This file is Peter Norvig’s compilation of the dictionary of words used in professional Scrabble tournaments. Each line in the file contains a single word.

Hint: use the Python random library for picking a random word.

Sample solution

To solve this exercise, you need to do three things:

  1. Read all the lists of words
  2. Generate a random number
  3. Take that word

Here is a sample solution:

Here is an alternate approach, with some comments:

  # import the random library
  import random

  # read all the list of words
  words = []
  with open('sowpods.txt', 'r') as f:
    line = f.readline().strip()
    words.append(line)
    while line:
      line = f.readline().strip()
      words.append(line)

  # generate a random number
  random_index = random.randint(0, len(words))

  # take the word
  print("Random word: ", words[random_index])

There are many solutions to every problem. Enjoy hacking around to find another solution!

Enjoying Practice Python?


Explore Yubico
Explore Yubico
comments powered by Disqus