Python: generate random integer not listed

I am very new to Python (and generally coding). I am trying to create a function that duplicates a list, with any instance of the string "rand" being replaced with a random integer. The function will be called several times, each time entering a new input_file. These new items should be added to the existing results list. We can assume that there will be no duplicate integers, but the string "rand" may appear many times. This is my current code. It is very close to what I want, except that when a random number is already in the list, it simply moves on to the next element, rather than trying to create a new random number. Can anyone help me with this? Thank you in advance.

import random
input_list = [1, 3, "rand", 2]
def number_adder(input_list):
  output_list = []

  for item in my_list:
    if item == "rand":
      new_variable = int(random.randint(0, 4))
      if new_variable in output_list:
        continue
    else:
      new_variable = item

  output_list.append(new_variable)
return output_list
+4
3
import random

input_list = [1, 3, "rand", 2]
output_list = []

options = set(range(5))
for item in input_list:
  if item == "rand":
    new_variable = random.choice(list(options))
  else:
    new_variable = item
  output_list.append(new_variable)
  options -= set([ new_variable ])

. , , , , .

set , , . , , choice set. , , .

, , , (, randint(0, 100000) 99990 ). .

, , :

def fill_randoms(list_with_randoms, options):
  for item in list_with_randoms:
    value = random.choice(list(options)) if item == 'rand' else item
    yield value
    options -= set([ value ])

:

list(fill_randoms([1, 3, "rand", 2], set(range(5))))

, .

+2

, . , :

import random
input_list = [1, 3, "rand", 2]

def rand_replacer(my_list):
    output_list = []
    for item in my_list:
        if item == "rand":
            while True:
                new_variable = random.randint(0, 4)
                if new_variable not in my_list:
                    output_list.append(new_variable)
                    break
        else:
            output_list.append(item)
    return output_list
+1

Loop while the number is in the output list:

if item == "rand": 
    new_variable = int(random.randint(0, 4))
    while new_variable in output_list:
        new_variable = int(random.randint(0, 4))
0
source

Source: https://habr.com/ru/post/1692218/


All Articles