Dev
Dev

Reputation: 586

copying the elements of a list to another list with a condition in python

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.

Upvotes: 0

Views: 906

Answers (2)

Zoom
Zoom

Reputation: 462

General 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)

We declare the two lists and enter a n_items x loop. We generate a random number and get the 1st number (number) greater than our generated random number. We count how many times we have seen this number previously and store it in n_same_numbers_in_list2. We check that "If we were to add this number to list_2 as well, would that be greater than n_items/2?". If not, we want to append number, else, we want to choose a random number in the range [1, 100] NOT in the range number and the number lesser than number from list_1 (if that exists, otherwise 0).

We can simplify a little by pre-generating the random list and only using a single for loop. We can also keep generating number_to_append until we get a number outside of the invalid range:

import random

list_1 = [5,12,22,37,65,100]
random_numbers = [random.randint(1, 100) for _ in list_1]
list_2 = []

n_items = len(list_1)

for i, (number, rand_number) in enumerate(zip(list_1, random_numbers)):
    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 = random.randint(1, 100)
            while number_to_append in range(lower_bound,upper_bound):
                number_to_append = random.randint(1, 100)
        list_2.append(number_to_append)
        break

print("Random number:", random_numbers)
print("List2", list_2)

Upvotes: 2

Faraaz Kurawle
Faraaz Kurawle

Reputation: 1148

First of all, why choosing random number from 0 to 100 when you just want to chose random number from the list it self? Use random.choice to chose randomly from a list.

Here's an smaller and simpler method

from random import choice
a=[5,12,22,37,65,100]
c=a.copy()
b=[]
for i in range(len(a)):
    num=choice(c)
    if b.count(num)>=(len(a)/2):
        c.remove(num)
        num=choice(c)
    else:
        
        b.append(num)
print(b)

Explantion:

  1. Took a copy of a in variable c using copy() function.
  2. Chose a number from the list c, and also checked if that particular number has been appended to the list b n\2 times.
  3. If it's True, then removed that particular number from list c and again chose a random number. (So that the number wont be repeated further)
  4. If it's False then appended that number in list b.

Upvotes: 0

Related Questions