def square(x):
int(x)
return 2(x * x)
def my_map(func, arg_list):
result = []
for i in arg_list:
result.append(func(i))
return result
squares = my_map(square, [1,2,3,4,5])
print(squares)
i'm trying to pass a number to a function and have it print the result, i have a function for the equation def square(), and a function that receives the numbers and the function
I keep on getting this error:
"TypeError: 'int' object is not callable"
I'm new to programming and was watching corey shaffer in YouTube and he wrote a program similar to this one. I started to play around with it, and now I'm stuck.
I would like the print statement to print out arg_list(i) and have I go through def square(x) and have that answer stored in result
here's a fix to your square function (you were missing a * operator)
def square(x):
int(x)
return 2*(x * x)
however, according to your function name I'm guessing you wanted the function to return the square of x:
2 --> 4
3 --> 9
4 --> 16
in that case, here's also a bug fix:
def square(x):
return x**2
The line 2(x * x) is causing python to treat the integer 2 as a function with arguments x*x, and hence the error "TypeError: 'int' object is not callable"
In [16]: x = 1
In [17]: 2(x*x)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-17-14e610e542ba> in <module>
----> 1 2(x*x)
TypeError: 'int' object is not callable
To square a number, you need x**2 instead, or perhaps pow(x, 2)using the pow builtin
def square(x):
int(x)
return x**2
The problem is with 2(x * x) statement. In the Python programming language, we need to explicitly mention all the operators in expressions. Like, the statement should be 2*(x*x) and when you use rounded brackets, you are actually calling the function.
Also, the above program can be reduced to,
In [54]: list(map(lambda no: int(no)**2, [1, 2, 3, 4, 5]))
Out[54]: [1, 4, 9, 16, 25]
Related
I've been watching Linear Algebra series made by 3Blue1Brown and I came up with this idea that I should write programs to compute the math, so I started to do it.
I wrote some methods. I wrote mul method for it. This method stretch out the vector by a given factor.
class Vector:
def __init__(self, data):
# [1]
# [1, 2, 3] --> [2]
# [3]
self.data = data
def __mul__(self, other):
if not isinstance(other, (int, float)):
raise TypeError("The second object(item) is not a number(integer, float)")
return Vector(list(map(lambda x: x * other, self.data)))
For example:
sample = Vector([1, 2])
When I execute this, it executes without errors:
print(sample * 10)
# it returns Vector([10, 20])
But when I execute this:
print(10 * sample)
It throws an error:
Traceback (most recent call last):
File "/home/jackson/Desktop/Matrices/MM.py", line 139, in <module>
print(10 * a)
TypeError: unsupported operand type(s) for *: 'int' and 'Vector'
I know the second one runs int.mul . So is there any way for the second one to behave like the first one?? Because technically there shouldn't be any difference between "Vector * int" and "int * Vector".
Here is the full code if you need --> link
Yes, you need to implement __rmul__ etc. See https://docs.python.org/3.7/reference/datamodel.html#emulating-numeric-types
Also, a really good linear algebra library already exists for python called numpy (but if you are implementing it yourself for learning purposes, just ignore that and have fun instead).
I'm having trouble understanding generators when they are used as arguments. Here are a couple cases where I don't fully understand the source of the errors, or at least how to work around them. Explicit fixes as well as broader explanations on the functionality/use of generators would be appreciated.
(I included 3 examples because I have a feeling they are all just facets of the same misunderstanding. I think the question would be better served as one post rather than 3. Please comment if you disagree.)
In the first example: I understand that generator objects cannot be added explicitly, but how should the script be modified to use (unpack?) the generators?
>>> def f(x): return x
>>> def g(x): yield x
>>> def h(x, y): return x + y
>>> h(f(3), f(4))
7
>>> h(g(3), g(4))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in h
TypeError: unsupported operand type(s) for +: 'generator' and 'generator'
In the second example: I'm having trouble understanding how a predefined generator object could be used to generate argument values for a function.
>>> print(*(x*2 for x in range(3)))
0 2 4
>>> print(x*2 for x in range(3))
<generator object <genexpr> at 0x7fc71f050db0>
>>> print(*(yld(x) for x in range(3)))
<generator object yld at 0x7fc71f050c50> <generator object yld at 0x7fc71f050ca8> <generator object yld at 0x7fc71f050e08>
In this third example, how could a generator be used for a multi-argument function?
def yld(x): yield x
(lambda x, y: x + y)(*(yld(x) for x in range(2)))
In David Beazley's talk on generators, he shows how to create a generator function from any single-argument function thus:
def generate(func):
def gen_func(s):
for item in s:
yield func(item)
return gen_func
and illustrates it with math.sqrt:
gen_sqrt = generate(math.sqrt)
for x in gen_sqrt(xrange(100)):
print x
So why does:
gen_sum = generate(sum)
for x in gen_sum([1,2,3,4,5]):
print x
produce:
TypeError Traceback (most recent call last)
<ipython-input-73-ef521f2bbfc8> in <module>()
1 gen_sum = generate(sum)
----> 2 for x in gen_sum(1):
3 print x
<ipython-input-50-3c0ba12c2429> in gen_func(s)
1 def generate(func):
2 def gen_func(s): # closure
----> 3 for item in s:
4 yield func(item)
5 return gen_func
TypeError: 'int' object is not iterable
Is it more accurate to say that the function being a single-argument function is a necessary but insufficient condition for this approach to work? And that the other necessary condition is that the single argument must be a single item (and not a sequence)?
You're passing a list whose elements are the wrong type. Of course it's not going to work, for the same reason that gen_sqrt(['a', 's', 'd', 'f']) wouldn't have worked.
You need to pass gen_sum a list of things it makes sense to call sum on, such as other lists:
for x in gen_sum([[1, 2], [3, 4]]):
print x
Output:
3
7
You are correct, both are necessary requirements:
def generate(func):
def gen_func(s):
for item in s: # <--- requires s to be interable
yield func(item) # <--- requires func to accept a single argument
return gen_func
So in
gen_sum = generate(func)
for x in gen_sum(s):
print x
func must accept a single argument and s must be iterable.
generate is the generator version of map.
map(lambda x: x*2, range(5)) [0, 2, 4, 6, 8]
It takes the input range and applies the function the each of the element in the range.
generate does the same, but it doesn't return a list. It yields the result of each transformation.
Now take a look at your example. What would be the first result? sum(1).
But sum expects a list, not an integer, hence the error message.
Im new to python and I was writing this simply code for finding the roots of the function:
from scipy import optimize
x = eval(raw_input()) #Initial guess
f = eval(raw_input()) # function to be evaluated
F = eval(raw_input()) #derivative of function f
round(optimize.newton(f, x, F, tol = 1.0e-9), 4)
But the interpreter returns:
TypeError: 'float' object is not callable
I'm really not sure what im missing out from this code. Can someone help me out..thank you in advance
optimize.newton expects a reference to a callable object (for example a function). That does not mean that you give a function as a string like 'x*x' but you have to define one first, like:
def my_func (x):
return x*x
Then you can plug my_func into optimize.newton (besides the other required parameters).
This will depend on what you are inputting for f. If you enter something like
lambda x: x ** 2
then it will be interpreted as a function, for example
In [83]: f = eval('lambda x: x ** 2')
In [84]: f(5)
Out[84]: 25
So, what im trying to do is get certain numbers from certain positions in a array of a given > range and put them into an equation
yy = arange(4)
xx = arange(5)
Area = ((xx[2] - xx[1])(yy[2] + yy[1])) / 2
I try to run it and I get this..
----> ((xx[2] - xx[1])(yy[2] + yy[1])) / 2
TypeError: 'numpy.int64' object is not callable
I get error.. how can I use certain numbers in an array and put them into an equation?
Python does not follow the same rules as written math. You must explicitly indicate multiplication.
Bad:
(a)(b)
(unless a is a function)
Good:
(a) * (b)
This error also occurs when your function has the same name as your return value
def samename(a, b):
samename = a*b
return samename
This might be a super rookie mistake, I am curious how often this answer will be helpful.
You are missing * when multiplying, try:
import numpy as np
yy = np.arange(4)
xx = np.arange(5)
Area = ((xx[2] - xx[1])*(yy[2] + yy[1])) / 2
This could happen because you have overwritten the name of the function that you attempt to call.
For example:
def x():
print("hello world")
...
x = 10.5
...
x()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
2 print("hello world")
3 x = 10.5
----> 4 x()
TypeError: 'float' object is not callable