Generate random numbers without repeating the previously generated number [duplicate]

1

I'm trying to make a program that simulates the game "Door of Hope" of Silvio Santos in Pyton and I need the program to generate a random number, excluding the number generated previously. I did this:

premio = rd.randint(1,3)

p = int(premio)

print(p)

w = rd.sample(range(1,3), p)

print(w)

But a warning appears saying that the sample is larger than the population. I do not know how to do it any other way!

Q: For those who want to help with the program as a whole, here's the question:

  

Make a program that simulates the behavior of Silvio Santos. Your   program should:

     
  • randomly choose one of the three doors and place the prize   behind it (do not tell the user where the prize is);
  •   
  • request   the user to choose one of three ports;       open a door that does not have the prize and that the user has not chosen (if there is more than one choice for the door to be   open,   your program should open any of them with equal probability);
  •   
  • show the user which port was opened;
  •   
  • Ask the user if he wants to keep his initial choice or if he wants to change the port;
  •   
  • show the user whether or not he won the prize.
  •   
        
    asked by anonymous 19.07.2017 / 21:33

    2 answers

    1

    First make a list of ports. Let's assume we are working with 10 ports.

    *l, = range(1,11)
    

    will generate:

    >>l
    [1,2,3,4,5,6,7,8,9,10]
    

    Now let's delete a random number from the list. Just shuffle the items and remove the last one. It will be the prize.

    import random
    random.shuffle(l)
    premio = l.pop()
    

    Ask the user to choose a port.

    user = input('Escolha uma porta de um a dez')
    

    Remove the port that the user chose from the list.

    try:
        l.remove(int(user))
    except:
        pass
    

    We use try / except to avoid a ValueError if it chooses the prize door (which is no longer on the list and thus can not be removed).

    We have already removed the door with the prize and the door that the user chose. Just shuffle again and take the last one: this port does not have the prize, nor was it chosen by the user.

    random.shuffle(l)
    print('A porta ' + str(l.pop()) + ' foi aberta')
    

    The rest of the program is trivial.

    Just compare the new chosen port, int (new) obtained from new = input (), or the maintained port, int (user), with the port stored in the prize variable.

        
    20.07.2017 / 20:21
    -1

    Just generate a number and add it to an array, then when it is to generate a new number, make a foreach or something like that to go through all the positions of the array, checking if any is equal to the new number generated. If it is, it generates a new number and the increment variable to 0 if there is no equal adds in the last filled position + 1

        
    20.07.2017 / 12:32