-1

I need help with creating a random string of 4 numbers without having duplicates.

Code:

from random import randint

correct = [randint(1,8), randint(1,8), randint(1,8), randint(1,8)]
usr_guess = [0, 0, 0, 0]
usr_guess_output = []
usr_guess_output_n = []
print(correct)

Also, if you could help me get the user input without needing commas that would be great!

Full code:

from random import randint

correct = [randint(1,8), randint(1,8), randint(1,8), randint(1,8)]
usr_guess = [0, 0, 0, 0]
usr_guess_output = []
usr_guess_output_n = []
print(correct)

guesses = 0

print('Welcome to Mastermind. Guess the combination of numbers between 1 and 8. If you get the correct number and place, a \'*\' will be printed. If you get the correct number but wrong place, a \'-\' will be printed. If you get it wrong completely, a \'#\' will be printed. The position of the output does not correlate to the positions in the actual list of numbers.')

while(True):
  usr_guess_output_n = []
  usr_guess_output = []
  correct_count = 0
  guesses += 1

#  try: #Makes sure that the program still works even if the user messes up the input

  usr_guess = input('Guess at the numbers (separate with commas) > ').split(',') #Splits the user input into a list of integers

  usr_guess = [int(x) for x in usr_guess ] #Converts all list items into integers for comparisons

  print('')
  i = 0
  for i in range(0,4): #Iterates the lists to check for comparisons

    if correct[i] == usr_guess[i]:
      usr_guess_output.append('*')
      correct_count += 1

    elif correct[i] in usr_guess:
      usr_guess_output.append('-')

    else:
      usr_guess_output.append('#')

  if(correct_count > 3):
    break

  for i in usr_guess_output:
    if i == '*':
      usr_guess_output_n.append('*')
  for i in usr_guess_output:
    if i == '-':
      usr_guess_output_n.append('-')
  for i in usr_guess_output:
    if i == '#':
      usr_guess_output_n.append('#')


  print(str(usr_guess_output_n).replace(',','').replace('[','').replace(']','').replace('\'',''))

#  except:
#    print('something went wrong. you probably input something other than an integer')
#    guesses -= 1

print('\nIt took you ' + str(guesses) + ' guesses!')
input('Press enter to exit')
1
  • use random.sample(range(1, 9), 4) Commented Feb 12, 2018 at 20:11

1 Answer 1

1

How about utilising a while loop?

correct = []
#list long enough?
while len(correct) < 4:
    #create random number
    rand_num = randint(1, 8)
    #not in the list?
    if rand_num not in correct:
        #include in list
        correct.append(rand_num)
Sign up to request clarification or add additional context in comments.

2 Comments

No. Just use random.sample
The documentation for random.sample

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.