[ create a new paste ] login | about

Link: http://codepad.org/2hEOlTqA    [ raw code | fork ]

Python, pasted on Jan 26:
import random
import sys

# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import string

WORDLIST_FILENAME = "words.txt"

def load_words():
    """
    Returns a list of valid words. Words are strings of lowercase letters.
    
    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print "Loading word list from file..."
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r', 0)
    # wordlist: list of strings
    wordlist = []
    for line in inFile:
        wordlist.append(line.strip().lower())
    print "  ", len(wordlist), "words loaded."
    return wordlist

def get_frequency_dict(sequence):
    """
    Returns a dictionary where the keys are elements of the sequence
    and the values are integer counts, for the number of times that
    an element is repeated in the sequence.

    sequence: string or list
    return: dictionary
    """
    # freqs: dictionary (element_type -> int)
    freq = {}
    for x in sequence:
        freq[x] = freq.get(x,0) + 1
    return freq


# Actually load the dictionary of words and point to it with 
# the wordlist variable so that it can be accessed from anywhere
# in the program.

import sys
wordlist = load_words()

def fragment_starts_word(fragment_str, wordlist):
    fragment_str_len = len(fragment_str)

    for word in wordlist:
        if word[0:fragment_str_len] == fragment_str:
            if len(word) > len(fragment_str):
                print "Fragment (%s) is start of at least one longer word (%s)" % (fragment_str, word)
                return True


def other(player):
    if player == 1:
        return 2
    else:
        return 1


def ghost():
    fragment = []
    player = 1
    fragment_str = ""

    while True:
        print "Fragment: " + fragment_str
        turn = raw_input("Enter your selection Player" + str(player) + ":")
        while len(turn) > 1 or turn not in string.ascii_letters:
            turn = raw_input("Please enter a single letter, only: ")
            
        fragment.append(turn.lower())  ##adds turn selection in lower case to fragment
        fragment_str = "".join(fragment)
    
        if fragment_str in wordlist:
            print fragment_str + " is a word."
            if len(fragment_str) > 3:
                print "You Lose!"
                break        
            
        elif fragment_starts_word(fragment_str, wordlist) != True:
            print "Fragment is not start of a word. You LOSE!"
            break    

        player = other(player)


Create a new paste based on this one


Comments: