1

Sorry for the confusing question. I have a list called switch that contains randomly chosen numbers between 10 and 30. I am trying to use these numbers in the following function (this is just the start):

def rewardfunc(y, switch): left_reward = [] right_reward = [] for x in range(switch[0]): left_reward.append(prob(y)) right_reward.append(prob(1-y)) for x in range(switch[1]): left_reward.append(prob(1-y)) right_reward.append(prob(y)) for x in range(switch[2]): left_reward.append(prob(y)) right_reward.append(prob(1-y)) for x in range(switch[3]): left_reward.append(prob(1-y)) right_reward.append(prob(y)) 

In this function, every number in switch is used to define a block of trials, but every other number defines a different kind block. So, my problem is how do I use every number in switch in order, while using every other number for a different task? Currently, I'm writing it out as for x in range((switch[0]))... is there a way to do this in a shorter form?

Hope my question makes sense. Thank you for any help.

0

3 Answers 3

1
for i, x in enumerate(switch): for _ in range(x): if i % 2 == 0: left_reward.append(prob(y)) right_reward.append(prob(1-y)) else: left_reward.append(prob(1-y)) right_reward.append(prob(y)) 
Sign up to request clarification or add additional context in comments.

Comments

0

On each iteration, just swap references to left_reward and right_reward. Something like

def rewardfunc(y, switch): l = left_reward = [] r = right_reward = [] for x1 in switch: for x2 in x1: l.append(prob(y)) r.append(prob(1-y)) l, r = r, l 

Comments

0

If you are a fan of comprehensions:

left_reward = [prob(1-y if i % 2 else y) for i in range(len(switch))] right_reward = [prob(y if i % 2 else 1-y) for i in range(len(switch))] 

If prob(e) is expensive at all then consider precalculating:

prob_y, prob_inv_y = prob(y), prob(1-y) left_reward = [prob_inv_y if i % 2 else prob_y for i in range(len(switch))] right_reward = [prob_y if i % 2 else prob_inv_y for i in range(len(switch))] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.