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)))
Related
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]
I have the following python statement
x = lambda :8()
checking the type of x returns the following
<class 'function'>
but then doing this
x()
TypeError: 'int' object is not callable
I can solve this by putting parenthesis around the lambda like so
x = (lambda :8)()
But I am wondering what is going on.
The problem does not lie with calling x, you are trying to call 8 with 8(). Calling an integer raises an error because instances of int are not callable.
I can solve this by putting parenthesis around the lambda like so
What you are doing with x = (lambda :8)() is construct an anonymous function that always returns the number 8, then call it, and assign the name x to the return value.
>>> x = (lambda :8)()
>>> x
8
However, x() will still raise an error because again it's trying to call an integer.
>>> x()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
a = 3
def f(x):
x = (x**3-4*x)/(3(x**2)-4)
return x
while True:
print(a)
a = f(a)
I'm getting a type error here, and I'm not sure why. I'm trying to run this recursive function, is there any way to fix this?
You need a * operator after your parentheses. Multiplication is only implied in mathematical notation in this context, in Python it looks like you're trying to call a function.
3(x**2)
So it would be
3*(x**2)
For example
>>> 3(5*2)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
3(5*2)
TypeError: 'int' object is not callable
>>> 3*(5*2)
30
I'm working on a simple size() method while working with Mutablelists and I keep getting the following error:
>>> xs = MutableList
>>> xs
<class __main__.MutableList at 0x02AC6848>
>>> xs.size()
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
xs
.size()
File "C:\Users\safim\Desktop\Python HW 4\a3_1.py", line 59, in size
for x in self :
TypeError: iteration over non-sequence
The code I used was:
result = 0
for x in self :
result + 1
return result
I appreciate the help in advance.
xs is the same object as MutableList, because you made it so:
xs = MutableList
The message printed even tells you this:
<class __main__.MutableList at 0x02AC6848>
As it says, xs is the class, not an instance of that class.
You can't call MutableList.size() (which is what you're trying to do, because xs and MutableList are the same thing) because that doesn't tell it what instance you want to use.
Did you mean to instantiate a MutableList? If so:
xs = MutableList()
Your other code won't work either, since result + 1 adds 1 to result and then throws away that number (you never assign it to a variable). Most likely you mean result += 1.
One of my coworkers was using the builtin max function (on Python 2.7), and he found a weird behavior.
By mistake, instead of using the keyword argument key (as in key=lambda n: n) to pre-sort the list passed as a parameter, he did:
>>> max([1,2,3,3], lambda n : n)
[1, 2, 3, 3]
He was doing what in the documentation is explained as:
If two or more positional arguments are provided, the largest of the positional arguments is returned., so now I'm curious about why this happens:
>>> (lambda n:n) < []
True
>>> def hello():
... pass
...
>>> hello < []
True
>>> len(hello)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'function' has no len()
I know it's not a big deal, but I'd appreciate if any of the stackoverflowers could explain how those comparisons are internally made (or point me into a direction where I can find that information). :-)
Thank you in advance!
Python 2 orders objects of different types rather arbitrarily. It did this to make lists always sortable, whatever the contents. Which direction that comparison comes out as is really not of importance, just that one always wins. As it happens, the C implementation falls back to comparing type names; lambda's type name is function, which sorts before list.
In Python 3, your code would raise an exception instead:
>>> (lambda n: n) < []
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: function() < list()
because, as you found out, supporting arbitrary comparisons mostly leads to hard-to-crack bugs.
Everything in Python (2) can be compared, but some are fairly nonsensical, as you've seen.
>>> (lambda n:n) < []
True
Python 3 resolves this, and produces exceptions instead.