Python Program is freezing up...

Started by
3 comments, last by Kylotan 15 years, 2 months ago
This is probably something stupid. The program does what it is supposed to do and then it freezes and won't allow the last line to execute and end the program btw this is for a class assignment...which is why it looks like it is. It's done other than this and nothing like this is covered in the book as far as i can tell.

import random

phrase = ("There", "was", "never", "a", "doubt", "that", "you", "would", "have",
        "the", "best", "of", "whatever", "that", "could", "have", "been",
        "had", "before", "we", "finished", "off", "your", "puny", "limited",
        "and", "short", "life")

used = []

for count in range(len(phrase)):
    word = random.choice(phrase)
    while word in used:
        word = random.choice(phrase)
    print word,
    if(count == len(phrase)-1):
        print "!"
    used.append(word)

raw_input(" ")

Advertisement
Based on a quick run through the debugger, your problem appears to be in lines 13 and 14, the while loop. As you put more and more words into the used list, your chances of randomly selecting an unused word from the list become smaller and smaller, causing your program to run for a long time until it finally picks all words from the list by chance. Here is an updated version that simply removes used words from the list, rather than storing them in a separate location (make sure you press Enter at the end of this new program to end it, because of raw_input()):

import randomphrase = ["There", "was", "never", "a", "doubt", "that", "you", "would", "have",        "the", "best", "of", "whatever", "that", "could", "have", "been",        "had", "before", "we", "finished", "off", "your", "puny", "limited",        "and", "short", "life"]for count in range(len(phrase)):    word = random.choice(phrase)    print word,    if(count == len(phrase)-1):        print "!"    phrase.remove(word)raw_input(" ")
Your program doesn't freeze, it just gets stuck in an infinite loop somewhere. Try to analyze your code carefully to see the bottleneck. Perhaps place a few additional print's so you can see what's going on. Hint: it has to do with how you're selecting unused words.
Create-ivity - a game development blog Mouseover for more information.
I thought that it might be that, but i figured that it wouldn't just stop like that... oh well thanks ^.^
Purely for the purposes of education, the whole program could pretty much be replaced with this:
import randomshuffled = list(phrase)random.shuffle(shuffled)print ' '.join(shuffled) + '!'raw_input(" ")


It's worth noting why you have to use the list constructor, and why random.shuffle is better than keeping your own 'used' list. And also it's worth looking up the function that would do something similar if you didn't want all the elements of 'phrase', just a subset.

This topic is closed to new replies.

Advertisement