-1

May my question is really simple, but I can't solve this. So I have my code where I have to user's input x and y. My method doesn't work

from scipy import signal
import numpy as np

x=np.array(input('Elements = ')
y=np.array(input('Elements = ')
h=signal.convolve(x,y)
print(h)
danel1
  • 1
  • 1
  • For one, you're missing closing parentheses on your input lines. And, you're not converting the input string into anything. If you need a user to enter multiple integers (or floats, you didn't specify), then you have to write code to handle that, not just try to throw the string into a numpy array. Without knowing what you want the users to input or what you want the format to be, it's impossible to help you here. Please specify. – Random Davis Sep 22 '20 at 16:23
  • 2
    Does this answer your question? [Get a list of numbers as input from the user](https://stackoverflow.com/questions/4663306/get-a-list-of-numbers-as-input-from-the-user) – Tomerikoo Sep 22 '20 at 16:31

2 Answers2

0

One solution is to use eval, EG:

from scipy import signal
import numpy as np

x=np.array(eval(input('Elements = ')))
y=np.array(eval(input('Elements = ')))
h=signal.convolve(x,y)
print(h)

Terminal output:

Elements = [1,2,3]
Elements = [4,5]
[ 4 13 22 15]

This approach is nice and simple, but be aware that using eval on user input can be dangerous (see EG here), so if you're going to use this approach, then make sure you trust whoever is going to use your program.

Jake Levi
  • 1,329
  • 11
  • 16
  • 2
    That's a very bad idea and advice to use `eval`, also it enforces the user to input the data in a Python like manner (`[...]`) – Tomerikoo Sep 22 '20 at 16:30
  • TBF I did qualify it with a warning about dangers of using `eval`. I don't think `eval` is *always* a bad idea, it depends on the context, IE if you don't know who will be using your program. If you can trust your users, then this approach has the advantage that a) it's nice and simple, and b) it is easy to input multi-dimensional arrays like this (EG `[[1, 2], [3, 4]]`) without having to change the source code – Jake Levi Sep 23 '20 at 12:26
0

List comprehension can be used to achieve this

from scipy import signal
import numpy as np
x=np.array([float(value) for value in input('Elements = ').split(',')])
y=np.array([float(value) for value in input('Elements = ').split(',')])
h=signal.convolve(x,y)
print(h) 

output:

Elements = 1, 2, 4
Elements = 3, 4,5
[ 3. 10. 25. 26. 20.]
Ajay Verma
  • 610
  • 2
  • 12