0

Right now I am trying to do a piece of code for the Monty Hall problem

I have some code that I am trying to fix and then enhance

This is one thing that I am stuck on:

I am trying to change the way the door at which the prize is chosen by using random.shuffle(), I have to use random.shuffle(), not anything else.

How would I do this?

What I have now does not work for that. if I put print(random.shuffle(door)), I don't get a new output. how do I make it return the chosen output

import random
door = ["goat","goat","car"]

choice = int(input("Door 1, 2 or 3? "))

otherDoor = 0
goatDoor = 0

if choice == 1:
    if door[1] == "goat":
        otherDoor = 3 
        goatDoor = 2
    elif door[2] == "goat":
        otherDoor = 2
        goatDoor = 3  
elif choice == 2:
    if door[0] == "goat":
        otherDoor = 3
        goatDoor = 1
    elif door[2] == "goat":
        otherDoor = 1
        goatDoor = 3
elif choice == 3:
 if door[0] == "goat":
     otherDoor = 2
     goatDoor = 1
 elif door[1] == "goat":
     otherDoor = 1
     goatDoor = 2

switch = input("There is a goat behind door " + str(goatDoor) +\
               " switch to door " + str(otherDoor) + "? (y/n) ")

if switch == "y":
    choice = otherDoor

if random.shuffle(door) == "car":
    print("You won a car!")
else:
    print("You won a goat!")

input("Press enter to exit.")

Community
  • 1
  • 1
matt6297
  • 81
  • 7
  • 4
    You need to pay closer attention to the [answers to the question you linked](https://stackoverflow.com/a/17649901/10077). `random.shuffle()` **does not return anything**. It shuffles the list in-place. – Fred Larson Nov 27 '17 at 17:18
  • `random.shuffle()` does just that... It shuffles the data. It's not *supposed* to output anything. – Mangohero1 Nov 27 '17 at 17:19

2 Answers2

1

random.shuffle shuffles in place, meaning it will return None if you try and assign a variable to it's non-existent output.

Since you say you have to use shuffle, you can shuffle the list in place with random.shuffle(door), then take an element from this shuffled list eg: door[0]

Varun Balupuri
  • 363
  • 5
  • 17
0

From the python3 documentation of the random module:

random.shuffle(x[, random]) Shuffle the sequence x in place.

The 'in place' means that the function is replacing the variable x (in your case, 'door') with a different variable that has the same values as before but with their order shuffled. It does not have a return, it simply modifies the variable you gave it, which is why your print statement shows 'None'.

If you must use, random.shuffle, you can simply select an element of the door after you've shuffled it (i.e. random.shuffle(door) then print(door[0])).

However, if other functions were to be an option, then random.sample(door,1) may be simpler instead (documentation for random.sample here).

JMikes
  • 572
  • 4
  • 12