Welcome, guest | Sign In | My Account | Store | Cart
2

I was writing code to do bootstrapping on a set of data. I wanted a test case where if I asked for one bootstrap I would be returned the original data. lambdas and function references saved me from inefficient code.

Python, 54 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
if bootstraps == 1:
  srri = lambda low, high, size: range(size) 
else:
  srri = scipy.random.random_integers

for boot in range(bootstraps):      
  for r in range(n1):
    for c in range(n0):
      sample_size = trial_result[r][c].size
      choices = srri(0, sample_size-1, sample_size)
      meas_grid[r,c] = pylab.array(trial_result[r][c][choices],dtype=float).mean()
  
  model_grid[:,:,:,boot], params[:,boot] = \
              process_grid(s0, s1, meas_grid)

#Instead of
srri = scipy.random.random_integers
if bootstraps == 1:
 for r in range(n1):
   for c in range(n0):
     meas_grid[r,c] = pylab.array(trial_result[r][c],dtype=float).mean()
  
 model_grid[:,:,:,boot], params[:,boot] = \
              process_grid(s0, s1, meas_grid)
else:
 for boot in range(bootstraps):
   for r in range(n1):
     for c in range(n0):
       sample_size = trial_result[r][c].size
       choices = srri(0, sample_size-1, sample_size)
       meas_grid[r,c] = pylab.array(trial_result[r][c][choices],dtype=float).mean()
  
   model_grid[:,:,:,boot], params[:,boot] = \
              process_grid(s0, s1, meas_grid)

#OR
srri = scipy.random.random_integers
for boot in range(bootstraps):
  if bootstraps == 1:
   for r in range(n1):
     for c in range(n0):
       meas_grid[r,c] = pylab.array(trial_result[r][c],dtype=float).mean()
  
    model_grid[:,:,:,boot], params[:,boot] = \
              process_grid(s0, s1, meas_grid)
  else:
   for r in range(n1):
     for c in range(n0):
       sample_size = trial_result[r][c].size
       choices = srri(0, sample_size-1, sample_size)
       meas_grid[r,c] = pylab.array(trial_result[r][c][choices],dtype=float).mean()
  
   model_grid[:,:,:,boot], params[:,boot] = \
              process_grid(s0, s1, meas_grid)

This is one example of how Python's lambdas and function references can help to make code more compact and readable

Add a comment

Sign in to comment

Created by kaushik.ghose on Fri, 27 Feb 2009 (MIT)
Python recipes (2836)
kaushik.ghose's recipes (8)

Required Modules

  • (none specified)

Other Information and Tasks