0

I want to generate 6 numbers from 1 to 49 while fulfilling the following conditions:

  1. One of the 6 numbers always has to be a number that the user inputs.
  2. No duplicates

I created this code.

      x2 = input()
      print("")
      print("Great! You will be able to get your lucky 
      numbers soon. Anwer Let's go! when you are ready.")
      Q2 = input()
      if Q2 == "Let's go!":
        print("")
        import random
        randomlist = random.sample(range(1, 49), 5)
        randomlist.insert(0, x2)
        print(randomlist)
        print("")

However, this code creates duplicates. What should I do?

cherry123
  • 49
  • 4
  • Does this answer your question? [How do I create a list of random numbers without duplicates?](https://stackoverflow.com/questions/9755538/how-do-i-create-a-list-of-random-numbers-without-duplicates) –  Mar 18 '21 at 02:05

2 Answers2

1

You can first create a list and then randomly pick an element from that list and then remove that element from the list. Do it for five times and then insert the input. You can do in this way:

import random
out = []
user = int(input())
out.append(user)
arr = [i for i in range(1,49)]
arr.remove(user)
for i in range(5):
    temp = random.choice(arr)
    out.append(temp)
    arr.remove(temp)
SAI SANTOSH CHIRAG
  • 2,046
  • 1
  • 10
  • 26
0

Put another way: the user chooses an integer in the range [1, 49]. Given that integer, sample five values from [1, 49] without replacement ("no duplicates") such that none of the values equal the user's choice.

Have the user choose:

user_value = int(input("Choose a value in [1, 49]: "))

assert user_value > 0 and user_value < 50

Generate the remaining integers:

from random import sample

# The set of candidates is every element in the range
# EXCEPT FOR the user's choice.
remainder = sample([i for i in range(1, 50) if i != user_value], 5)

remainder.append(user_value)
crcvd
  • 1,465
  • 1
  • 12
  • 23