[Tutor] Lists

Steven D'Aprano steve at pearwood.info
Fri Jun 10 12:25:34 CEST 2011


Vincent Balmori wrote:
> I'm stuck on two problems from the Absolute Beginners book. The first is simple. 
> I am trying to print all the words in the list in random order without repeats, 
> but it always shows None for some reason.
> 
> #Program prints list of words in random order with no repeats
> 
> import random
> 
> #List of words
> 
> list = ["first", "second", "third", "fourth","fifth"]
> 
> #Randomize word order
> 
> order = random.shuffle(list)


shuffle() does not return a new list, it shuffles in place, and returns 
None. So order will always be assigned the value None.

What you want is to make a copy of your word list, and shuffle that.

words = ["first", "second", "third", "fourth","fifth"]
shuffled = words[:]  # make a copy using slice notation [:]
random.shuffle(shuffled)


> The other question is: "Improve the program by adding a choice that lets the 
> user enter a name and get back a grandfather. You should still only use one list 
> of son-father pairs. Make sure to include several generations in list so a match 
> can be found." The only thing I have done is adding choice 5 with its basic elif 
> block and adding another name in each of the three sequences in the list, but I 
> am completely stuck otherwise.
> 
> #User can enter name of male and name of his father will show
> #Allow user to add, replace, and delete son-father pairs.
> #Also have the user enter a name to get back a grandfather
> 
> #Setting values
> sondad = {"Vincent": "Ramon": "Lolo","Jesus": "God": "Unknown", "Simba": 
> "Mufasa": "Lion"}

That can't work, you will get a syntax error. Each pair of key:value 
must be separated by a comma, not a colon, and you can't have key:key:value.

Since you can't do son:father:grandfather, you need another strategy. 
Fortunately there is a simple one: father is the son of grandfather. So 
your dict becomes:

sondad = {
     "Vincent": "Ramon",
     "Ramon": "Lolo",
     "Hermes": "Zeus",
     "Apollo": "Zeus",
     "Zeus": "Cronus",
     "Cronus": "Uranus",
     "Jesus": "God the Demiurge, the false God",
     "God the Demiurge, the false God":
         "God the Monad, the One, The Absolute, Bythos, Aion teleos",
     "Simba": "Mufasa",
     "Mufasa": "Lion",
     "Bart Simpson": "Homer Simpson",
     "Homer Simpson": "Abe Simpson",
     }


Try that and see how you go.



-- 
Steven


More information about the Tutor mailing list