#๐Ÿ”’ How can I improve my function?

25 messages ยท Page 1 of 1 (latest)

shell sinew
#

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?

vestal zealotBOT
#

@shell sinew

Python help channel opened

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.

solid canyon
#
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)
shell sinew
#

Oh wow that was a fast answer, I'll look at it and I'm sure I'll have some questions 1 minute

shell sinew
solid canyon
#

Yes, it is a Python gimmick. You should probably use the second code snippet.

shell sinew
#

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 ๐Ÿ˜›

solid canyon
#

Sure, you can also go up untill the sqrt of i

#

You don't need to check all primes up until i

shell sinew
#

true

#

So the flag is slightly faster

solid canyon
#

Seems like it, but Python should not be used if you want speed ๐Ÿ˜›

shell sinew
#

I know ๐Ÿ˜‚

#

I'm just curious is all

#

Optimisation is still nice ๐Ÿ˜‚

vestal zealotBOT
#
Python help channel closed

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?