0

How to solve Python Generator practice

Hey, I am a little stuck at the Generator practice lesson in the Python course. I've completed the code and in generates a list of prime numbers. But it always fails the last Test case, which is hidden. Do you guys have any suggestions? https://code.sololearn.com/cx7AuNJ89m1S/?ref=app

11th Oct 2023, 10:38 AM
H P
H P - avatar
6 Answers
+ 6
Quantum , you are right ... > to avoid the counter in the while loop, we could use a for loop instead like: ... def primeGenerator(a, b): for a in range(a, b): if isPrime(a) == True: yield a ... > the given code by sololearn can also be optimized: in the *isPrime()* function the number of 2 is handled in an if conditional, so we don't need to include this number also in the following range and can start with 3: ... elif x == 2: return True for n in range(3, x): # was for n in range(2, x): ...
11th Oct 2023, 5:51 PM
Lothar
Lothar - avatar
+ 2
I think you should remove the "equal to" from the while condition.
11th Oct 2023, 11:22 AM
Jan
Jan - avatar
+ 2
Lothar I also used a for loop when I solved it long time ago, so I just compared my for loop with his while loop, and that's why I advised him to remove the "equal to" from the while loop.
11th Oct 2023, 6:23 PM
Jan
Jan - avatar
+ 1
Quantum, I also used for loop to solve the question. I did mentioned the sentence included a keyword, which is RANGE. So the result list will include f (first), but not t (tail). At first try I wrote for num in range(a, b+1), where b=t, because I though the list includes tail. Of course it failed in test. Since we can view the expected output on test case 1, by hard coding t = 17, we can observe the result and make correction. Somehow, the sentence also said "between the two arguments". If it is really "between", then tail should be in the result too! All in all, the description is not actually precise.
12th Oct 2023, 3:39 AM
Wong Hei Ming
Wong Hei Ming - avatar
0
In the description it says: Use the isPrime() function to output the prime numbers in the given range (between the two arguments). There is 1 keyword in above sentence. And I think SoloLearn improved the description too. I maybe wrong if my memory failed. If in doubt, why not "hard code" f and t and see the result?
11th Oct 2023, 10:53 AM
Wong Hei Ming
Wong Hei Ming - avatar
0
I did it, the keyword in the assignment is "BETWEEN", which doesn't include the "t". So remove the "+ 1 " in the for loop "range(a, b + 1) and it should also work for Case4
9th Mar 2024, 12:33 PM
Abdi