Skip to content

Instantly share code, notes, and snippets.

@BrianHicks
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BrianHicks/9061846 to your computer and use it in GitHub Desktop.
Save BrianHicks/9061846 to your computer and use it in GitHub Desktop.

Think Python

Chapters 9-12

Chapter 9

Word Play

DEMO

9.1

Write a program that reads words.txt and prints only the words with more than 20 characters (not counting whitespace).

words = open('words.txt')

for word in words:
    word = word.strip()
    if len(word) > 20:
        print word

Output:

counterdemonstrations
hyperaggressivenesses
microminiaturizations

9.2

def has_no_e(word):
    return 'e' not in word
    
def pct_no_e(words):
    number_no_e = 0.0
    for word in words:
        if has_no_e(word):
            number_no_e += 1
    
    return number_no_e / len(words)
    
pct_no_e(words)

9.3

def avoids(word, chars):
    for char in chars:
        if char in word:
            return False
    return True

def number_avoid(words):
    words_which_avoid = 0.0
    chars = raw_input('Enter forbidden characters: ')
    for word in words:
        if avoids(word, chars):
            words_which_avoid += 1
    
    print words_which_avoid

Got which five-letter combo has the most words? It's qkjzw, with 91,293 words (80.22%)

9.4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment