0

I am dealing with a function that looks like this:

def A(x):
   A=range(n)
   A[0]=(bx[0] if condition1 else cx[0])
   for i in range(1,n):
            A[i]=((dx[i] if condition2 else ex[i])

   return  map(lambda x: x+3, A)

where A is a list and b,c,d,e are operations that take x as variable. Basically, I need to make an if statement for the first value in the A-list, and a different if statement for any other value apart from the first one. Is there a way to make this more efficient?

thank you

Luca91
  • 541
  • 1
  • 7
  • 19

2 Answers2

3

You can use np.where

import numpy as np
def A(x):
   A = np.arange(n)
   A[0] = (bx[0] if condition1 else cx[0])
   A[1:] = np.where(condition2, dx[1:], ex[1:])

   return A + 3
Priyatham
  • 2,821
  • 1
  • 19
  • 33
2

In terms of code restructuring - at least 2 optimizations can be applied in that context:

  • prevent double range() call
  • prevent redundant looping caused by map call (just to add 3 to each item)

Optimized version:

def func(x):
   res = [((bx[0] if condition1 else cx[0]) if i == 0 
          else (dx[i] if condition2 else ex[i])) + 3 
          for i in range(0, n)]

   return res
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105