Reputation: 3249
The code below provides an unexpected answer when I use raw_input. Can anyone explain me what is happening and how to solve it?
import numpy as np
response = raw_input("What is your move? ")
response=np.array(response)
changingPositions=np.flatnonzero(response)
print changingPositions
response=np.array([0,1,0])
changingPositions=np.flatnonzero(response)
print changingPositions
The execution is:
What is your move? [0,1,0]
[0]
[1]
The expected answer is
[1]
Upvotes: 0
Views: 66
Reputation: 1044
response is a string element. But you want an list.
so you need to parse the user input to a list. You should use input()
instead of raw_input()
, which parses the user input, or use eval(raw_input())
(eval()
parses a string to an element...
But I suggest to surround this function with try..except, to check if the user input is valid, and also loop if input is still invalid:
import numpy as np
isValid = False
while !isValid:
try:
response = input("What is your move? ")
isValid = True
except:
print("Input is not valid!!")
response=np.array(response)
changingPositions=np.flatnonzero(response)
print changingPositions
response=np.array([0,1,0])
changingPositions=np.flatnonzero(response)
print changingPositions
Upvotes: 1
Reputation: 22989
raw_input
returns a string, in fact np.flatnonzero(np.array('adfsgh'))
produces array([0])
too. So just make a list of ints:
In [1]: import numpy as np
In [2]: response = raw_input("What is your move? ")
What is your move? 0,1,0
In [3]: positions = np.array(map(int, response.split(',')))
In [4]: changing_positions = np.flatnonzero(positions)
In [5]: changing_positions
Out[5]: array([1])
Upvotes: 2