Reputation: 25
Hello all I would like to make a program that takes in two user inputs. The first is a scalar and the second is a provided list or array. The number would be a multiplier for which to scale the array and the output would be the multiplied array.
import numpy as np
a = [1, 3, 5, 7, 9]
b = [2, 4, 6, 8, 10]
Also, for added convenience to the user, I'd like there to be a default scalar of 1 if no number is entered.
I am sorry for the lack of code but everything I've tried has not worked anyway.
I know that using
x, y = input().split()
will enable the user to enter two inputs such as
3 a
or
5.5 b
which is how I'd like the inputs to be entered. However, while the number can be converted to a float, I do not know how to interpret the letter a or b from a string to the their array names.
float(x)*np.array(y)
The following error I believe to have occurred due to the mismatch of data types.
float(x)*np.array(y)
TypeError: ufunc 'multiply' did not contain a loop with signature matching types dtype('<U32') dtype('<U32') dtype('<U32')
If anyone can offer a solution or if there is a better way to do this than your input would be greatly appreciated. Thank you.
Upvotes: 0
Views: 241
Reputation: 8188
I guess this helps! This also handles the case where the user doesn't specify a multiplier, then it automatically defaults to 1
import numpy as np
a = np.array([1, 3, 5, 7, 9])
b = np.array([2, 4, 6, 8, 10])
y,*x = input().split()
if not x:
x=[1]
print(float(x[0])*eval(y))
Upvotes: 2
Reputation: 277
There are two solutions for your issue, one is cleaner.
The first one (dirty) consists in using eval
, because the a
or b
your user will pass as input will be evaluated as a string, not as your variable named a
.
So you have to return float(x) * eval(y)
.
But the use of eval
is heavily discouraged.
I think a cleaner way is to declare your pre-defined arrays in a dict
and to look for the key the user provided like that:
import numpy as np
arrays = {
"a": np.array([1, 3, 5, 7, 9]),
"b": np.array([2, 4, 6, 8, 10])
}
coefficient, array_name = input().split()
print(float(coefficient) * arrays[array_name])
NB: In your original code, a = [1, 3, 5, 7, 9]
defines a list. And you cannot multiply a float
and a list. You could eventually multiply and int
and a list but that is not what you want, it will duplicate your list :)
Upvotes: 1