I have a list, say list_1 = [5,12,22,37,65,100], now I want to copy the elements of this list to another list say list_2 which will also have the same number of elements, i.e in this case = 6. I just want to run a loop for 6 times and generate 6 different random numbers and depending on the values of random numbers I want a take an element from list_1 and copy that to list_2 using the below logic (For the generated random number take the next higher number from the list):
x=(random.randint(1, 100))
print(f"Generated random number: {x}")
list_1=[5,12,22,37,65,100]
for i in list_1:
if i>x:
print(i)
break
But the catch is one number is not allowed more than n/2 times. In this case, no number can come from list_1 more than 3 times. If the 1st 3 generated random numbers are : 55, 61 and 58 then the first 3 elements of list_2 will be = [65,65,65], so 65 can’t be copied anymore. In that case I wanted to use the logic as :
from random import choice
print(choice([i for i in range(1,100) if i not in range(37,65)]))
But unable to get the proper and desired output. Please help.
>Solution :
import random
from random import choice
list_1 = [5,12,22,37,65,100]
list_2 = []
n_items = len(list_1)
for _ in range(n_items):
rand_number = random.randint(1, 100)
print(f"Generated random number: {rand_number}")
for i, number in enumerate(list_1):
if number > rand_number:
n_same_numbers_in_list2 = sum(l2i == number for l2i in list_2)
if (n_same_numbers_in_list2+1) <= n_items/2:
number_to_append = number
else:
lower_bound = list_1[i-1] if i > 0 else 0
upper_bound = number
number_to_append = choice([i for i in range(1,100) if i not in range(lower_bound,upper_bound)])
list_2.append(number_to_append)
break
print(list_2)