1
import numpy as np
def Vin(t):
    inputs = []
    for i in range (1000):
        if (-1)**(np.floor( 2 * t[i] )) == 1:
            Vin = (1)
            inputs.append(Vin)
        else:
            Vin = (-1)
            inputs.append(Vin)

        return inputs

when I use this function on a range of t values, I only get one result,

i.e.

input1=Vin(tpoints)
print (input1)

only gives [1], whereas I want the function to do it for every t value.

Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49
chknpie
  • 33
  • 1
  • 3

3 Answers3

3

As others said, there's an indentation error in your return statement. I couldn't resist rewriting your code in a more pythonic way, avoiding all that cumbersome loops and the resulting errors:

return [1 if (-1)**(np.floor( 2 * t[i] )) == 1 else -1 for i in range (1000)]

that list comprenhension + ternary construction statement creates your -1,1 array in 1 line, much faster than you'd write with a loop.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

You are returning from with in the for loop,So you would return from the function on first iteration of the loop.

you may re-writ e the function as following

Code

def Vin(t):
    inputs = []
    for i in range (1000):
        if (-1)**(np.floor( 2 * t[i] )) == 1:
            inputs.append(1)
        else:
            inputs.append(-1)
    return inputs

Check the indentation of return inputs in the function here .

BTW, your function can be reduced to as more pythonic and efficient code

def Vin(t):
 reduce map(lambda x:int((-1)**(np.floor( t[i] < 1))), range (1000))
0

try:

 for i in range (1000):
        if (-1)**(np.floor( 2 * t[i] )) == 1:
            Vin = (1)
            inputs.append(Vin)
        else:
            Vin = (-1)
            inputs.append(Vin)

 return inputs

Current indentation of return , exits the for loop after 1st iteration

apomene
  • 14,282
  • 9
  • 46
  • 72