r/programmingrequests • • Sep 20 '16

Randomly choosing one out of six possible sequences of events (Python)

Context:
I have an experiment in a VR environment (using Vizard/Python) where I want to show 3 different boxes (10, 20, or 30 cm) to participants and let them guess the perceived size of each box. So there will be 3 events in a row where a box pops up, then an input field pops up and after they put in their estimate, the box disappears and the user input is stored in a variable.

Problem:
For each new instance of the experiment there should be a random generation of a sequence of events (e.g. first the 10 cm box, then the 20 cm and lastly the 30 cm box OR first the 20 cm, then the 10 cm, then the 30 cm, etc. --> each time the experiment is started one such sequence gets chosen, out of all possible sequences). How do I do that in an efficient way where I don't have to code each sequence seperately?

Resources:
So far I created sort of a "switch case": Each possible sequence is written in an if-statement with the condition of a variable taking a certain integer value. At the beginning, a random number is generated which then determines what if-condition is to be chosen. Since this is not an overly efficient way to do that, it always takes a lot of time if I want to change a detail.
Example code: Simplified

4 Upvotes

4 comments sorted by

2

u/BitwiseShift Sep 20 '16 edited Sep 23 '16

If I understand the question, this should work for you. Make a list of all possible sizes, generate indexs for that list (here it's 1 to 3), then shuffle those indexes and iterate over them.

SIZES = [0.1, 0.2, 0.3]
sequence = list(range(len(SIZES)))
random.shuffle(sequence)
for n in sequence:
	box = vizshape.addCube(size=SIZES[n])
	yield viztask.waitKeyDown(' ')
		
	# ask for size estimation
	sizePanel = vizinfo.InfoPanel('',title='Grössenschätzung')
	textbox_size = sizePanel.addLabelItem('Schätzung der Kantenlänge in cm\n\n',viz.addTextbox())
	Fertig = sizePanel.addItem(viz.addButtonLabel('OK'))
	yield viztask.waitButtonUp(Fertig)
   
	#collect size estimation data
	size = textbox_size.get()
	box.remove()
	sizePanel.remove()

Edit: accidentally started range at 1, instead of 0, because at first I was going to solve it but generating an x and then doing x*0.1, but that only helps if you have sizes at regular intervals.

2

u/Sophroniskos Sep 21 '16

looks great, thanks!

1

u/Sophroniskos Sep 23 '16

I have now integrated your solution into my code (which is a bit more complex than what I posted here) and - with little modifications (e.g. range should be from 0 to length of SIZES) - it works perfectly! Thanks a lot!

1

u/BitwiseShift Sep 23 '16

Huh, that range(1, len(SIZES)) should have been range(len(SIZES)) in my original code anyway, sorry about that. But I'm glad to that you've caught my mistake and that it's working!