Python - 创建没有重复的随机数字符串

时间:2018-02-12 20:06:07

标签: python python-3.x random

我需要帮助创建一个包含4个数字的随机字符串而不需要重复。

代码:

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)

另外,如果你可以帮助我获取用户输入而不需要逗号会很棒!

完整代码:

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 个答案:

答案 0 :(得分:1)

如何使用while循环?

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)