Keep reducing values in a list until all of them are 0

Viewed 114

I have an initial list called origin_list. I want to pick a position in this list at random and reduce the value of that positional element by 1 until all of them are 0. What would the fastest way to do this be?

I have some rather inaccurate pseudo-code below to get an idea of what I'm trying to do

import numpy as np
origin_list = [120,240,201]
while all(origin_list)>=0:
    rand_int = np.random.randint(0,len(origin_list))
    origin_list[rand_int] = origin_list[rand_int]-1
    if origin_list[rand_int]==0:
    # Continue with reducing only the non-zero elements in the list

2 Answers

You don't really need Numpy here — since you explicitly want to loop over values it doesn't add much. You could just take a list of indices of your list and use the random module to choose one. When that list reaches zero, remove the index. When the list of indices is empty stop:

import random

origin_list = [5,4,7]
positions = list(range(len(origin_list)))
                 
while positions:
    p = random.choice(positions)  
 
    # do something
    
    origin_list[p] -= 1 
    if origin_list[p] == 0:
        positions.remove(p)  

print(origin_list)
# [0, 0, 0]    
   

The efficiency is probably going to depend mostly on the part # do something.

I have slightly modified your pseudo-code to do your task.

import numpy as np

origin_list = [120,240,201]
index_list = list(range(len(origin_list))) # For keeping track of all remaining indexes(for which origin_list is not 0)

while len(index_list) != 0:
    rand_int = np.random.randint(0,len(index_list))
    index = index_list[rand_int] # Choosing random index from remaining indexes where data is > 0
    
    origin_list[index] = origin_list[index]-1
    
    # Do your task here

    if origin_list[index]==0:
        index_list.pop(rand_int) # Removing that index from available list of indexes     

I am basically just maintaining the available list of indexes where origin_list's value is greater than 0.

Each index will be removed from the list where its related element in the origin_list reaches 0.

Related