I have this function py def get_fast_primes(): primes = [] for i in range(2, 1000): for prime in primes: if i%prime == 0: continue primes.append(i)
My intention was for the continue to continue the outer for loop. Is there a way to do that with a different statement such as end or exit?
#๐ How can I improve my function?
25 messages ยท Page 1 of 1 (latest)
@shell sinew
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
Closes after a period of inactivity, or when you send !close.
def get_fast_primes():
primes = []
for i in range(2, 1000):
for prime in primes:
if i%prime == 0:
break
else:
primes.append(i)
This does what you want
When the if statement is True, it will end the inner loop with break.
The else is on the same line as the inner for. for/else means that when for completes without breaking, the else will execute.
@shell sinew
You could also use a flag:
def get_fast_primes():
primes = []
for i in range(2, 1000):
is_prime = True # Assume the number is prime
for prime in primes:
if i%prime == 0:
is_prime = False # Turns out, not prime ..
break
if is_prime:
primes.append(i)
Oh wow that was a fast answer, I'll look at it and I'm sure I'll have some questions 1 minute
I've never seen a for else block before, so the else executes when the for loop is not broken? py for prime in primes: if i%prime == 0: break else: primes.append(i)
Yes, it is a Python gimmick. You should probably use the second code snippet.
Maybe but I love the idea of this for else block ๐
The 2nd snippet is also very clean
The point of this was I wanted to optimise a function that I saw on youtube just for my own curiosity so I'll test both and tell you the results ๐
Sure, you can also go up untill the sqrt of i
You don't need to check all primes up until i
Seems like it, but Python should not be used if you want speed ๐
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.
๐ How can I improve my function?