[Tutor] Random order program

Andreas Perstinger andreas.perstinger at gmx.net
Mon Nov 28 00:24:47 CET 2011


On 2011-11-27 23:17, myles broomes wrote:
> #get the users input for the list of words, one by one
> first_word = input("Please enter your first word: ")
> second_word = input("Please enter your second word: ")
> third_word = input("Please enter your third word: ")
> fourth_word = input("Please enter your fourth word: ")
> fifth_word = input("Please enter your fifth word: ")
>
> #create a tuple containing the users words of the words
> word_list = (first_word,second_word,third_word,fourth_word,fifth_word)

You could shorten the input procedure by using a for-loop and appending 
every word to a list instead using five different "word"-variables and 
building a tuple with them.

> #create an empty list that the words will go into to be returned in a random order
> random_word_list = []
>
> print("Now your list will be displayed in a random order.")
>
> #random order list
> while len(random_word_list) != len(word_list):
>          word = random.choice(word_list)
>          if word not in random_word_list:
>                  random_word_list += word

Bob told you already that you are creating an infinite-loop. Try this:

Python 3.2 (r32:88445, Mar 25 2011, 19:28:28)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> l = []
 >>> s = "test"
 >>> l += s
 >>> l
['t', 'e', 's', 't']

Do you see your problem? You want to "add" a string to a list but with 
the inplace operator "+=" "word" is interpreted as a sequence (a list of 
letters). You can't "add" a string to a list:

 >>> l = l + s
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list

If you want to add an element to a list you should use the 
".append"-method of lists:
http://docs.python.org/py3k/tutorial/datastructures.html#more-on-lists

Bob mentioned also the problem with your algorithm. Everytime you get a 
word from "random.choice" which is already in "random_word_list" you 
have to loop again:

 >>> counter = 0
 >>> random_word_list = []
 >>> word_list = ["a", "b", "c", "d", "e"]
 >>> while len(random_word_list) != len(word_list):
...   counter += 1
...   word = random.choice(word_list)
...   if word not in random_word_list:
...     random_word_list.append(word)
...
 >>> print(counter)

If you are lucky, "counter" is close to the minimum 5. But in one of my 
test runs it was 25.
This is unnecessary because you don't need more iterations than the 
length of "word_list" (5 in your case)

Anyways, there is already a shuffle-method in the "random"-module:
docs.python.org/py3k/library/random.html

Bye, Andreas


More information about the Tutor mailing list