+ 3
I don't understand why it won't work pls help
29 Antworten
+ 4
What is the problem ? I don't even understand your code. in the function generate, what is the purpose of x if you're just going to ignore it ? Also, that's not how generators work, printing the generator will return the generator object, and not the values it has.
+ 3
You have created that generator object successfully, and if you print it, you see it's 'name'.
Now if you want to get the next value out, you need to use next() on it.
Instead of your print statement, try this:
p = generate(peter)
print(next(p))
print(next(p))
print(next(p))
+ 2
+ 1
Peter Paulinus Polycarp the asterisk decomposes a list (best explanation I could think of), if let say you have a function that takes three arguments f(a, b, c), and you want to input a list l = [a, b, c] as the three parameters, you'll get an error running f(l), but with f(*l), you're extracting all the values in the list. Same goes in this case, you're extracting the values and printing them all.
+ 1
Peter Paulinus Polycarp just to mention one last thing. The best way generators should be used is like what HonFu did. If you just convert the generator to a list, then you're throwing away the whole concept of generators.
+ 1
Aymane Boukrouh [Unavailable] I've got it now, but what do u mean by throwing away the concept away the whole concept of generator. If I use list comprehension it won't work
+ 1
Peter Paulinus Polycarp how did you try it ?
+ 1
https://code.sololearn.com/cxIxyGuccUl2/?ref=app
It keeps repeating my input for the said range
+ 1
Okay, what is your desired output ? I'm confused
+ 1
The point of generators is, that you don't create all values at once, but only always the next one, as you need it.
That's what next does.
You can imagine a generator object as a coffee machine: when you press 'next', another cup of coffee is made. ;-)
for loops also do this: They call next, next, next.
If you just make it a list, there's not really a point to create a generator in the first place, because now you create all the C a values at once.
+ 1
I think i found where u get it wrong... Check it out here
https://code.sololearn.com/cb40H5sPHLOj/?ref=app
+ 1
Aymane Boukrouh [Unavailable] I think I get my mistake now .
+ 1
Aymane Boukrouh [Unavailable] I'm grateful thanks 4 ur time
+ 1
Ruchika Tripathi don't spam, spamming may lead to a temporaty ban
+ 1
You can do like this : yield 2*p and 10**x
But I still don't know what the code supposed to do
+ 1
Me too
0
HonFu pls , why the next function
0
Peter Paulinus Polycarp this is very basic manipulation of generators, the next function is literally the first fuction taught after generators. Please review the course.
0
Alexandr pls I get the need for the for loop but why the asterisk
0
Aymane Boukrouh [Unavailable] pls I didn't ignore the argument x I used it in the for loop and the yield or maybe you can xplain what u meant by ignore