I have written a loop that samples from an existing pool of images to create a (pseudo-)randomized list. The goal is to have a list where the images appear a specific number of times but without consecutively repeating the same image.
I have tried the following code:
import random
number_img1 = number_img2 = 2
number_img3 = number_img4 = 4
number_img5 = number_img6 = 6
total_images = number_img1 + number_img2 + \
number_img3 + number_img4 + number_img5 + number_img6
stimulus_full_random = []
new_item = 0
while len(stimulus_full_random) < total_images:
new_item = random.choice(stimulus_full)
if len(stimulus_full_random) == 0:
stimulus_full_random.append(new_item)
elif 0 < len(stimulus_full_random) < total_images:
if new_item == "img1_full" and stimulus_full_random.count("img1_full") < number_img1:
if new_item != stimulus_full_random[-1]:
stimulus_full_random.append(new_item)
else:
stimulus_full_random[-1] = new_item
elif new_item == "img2_full" and stimulus_full_random.count("img2_full") < number_img2:
if new_item != stimulus_full_random[-1]:
stimulus_full_random.append(new_item)
else:
stimulus_full_random[-1] = new_item
elif new_item == "img3_full" and stimulus_full_random.count("img3_full") < number_img3:
if new_item != stimulus_full_random[-1]:
stimulus_full_random.append(new_item)
else:
stimulus_full_random[-1] = new_item
elif new_item == "img4_full" and stimulus_full_random.count("img4_full") < number_img4:
if new_item != stimulus_full_random[-1]:
stimulus_full_random.append(new_item)
else:
stimulus_full_random[-1] = new_item
elif new_item == "img5_full" and stimulus_full_random.count("img5_full") < number_img5:
if new_item != stimulus_full_random[-1]:
stimulus_full_random.append(new_item)
else:
stimulus_full_random[-1] = new_item
elif new_item == "img6_full" and stimulus_full_random.count("img6_full") < number_img6:
if new_item != stimulus_full_random[-1]:
stimulus_full_random.append(new_item)
else:
stimulus_full_random[-1] = new_item
else:
break
print(stimulus_full_random)
In some cases, it produces the desired output but sometimes, the loop does not break / the program runs on forever. I have tried several different versions, but always the same result. I am fairly new to programming and I do not understand why (only in some instances) this code does not work. Help is very much appreciated!
Aucun commentaire:
Enregistrer un commentaire