Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Escape indentation
#1
Hello,

Its probably the wrong way to do this, but i am trying to print my list and because of the if statement to get rid of the false returned, i ended up with doubles in my list.

prime = []
def is_prime_v1(n):
    
    if n == 1:
     return False
    
    for d in range(2, n):
        if n % d == 0:
            return False
    prime.append(n)
    return n
  
for n in range(1,21):
  if is_prime_v1(n) != False:
    print(is_prime_v1(n))
   
print(prime)  
Output:
2 3 5 7 11 13 17 19 [2, 2, 3, 3, 5, 5, 7, 7, 11, 11, 13, 13, 17, 17, 19, 19] >
print(prime) seems to be prisonner of the for indent. It cause the numbers to repeat twice.
How to avoid this?
Of course the Sieve of Eratosthenes is more efficent. The question is just about controling the return and indentation.

Thank you
Reply
#2
On line 15 you are callingis_prime_v1(n)a second time. Try it like this:
prime = []
def is_prime_v1(n):
     
    if n == 1:
     return False
     
    for d in range(2, n):
        if n % d == 0:
            return False
    prime.append(n)
    return n
   
for n in range(1,21):
  prime_number = is_prime_v1(n)
  if prime_number != False:
    print(prime_number)
    
print(prime)  
Frankduc likes this post
Reply
#3
Wonder what is the principle idea behind the scene to be force to create a new variable to escape the indent.
Thanks!
Reply
#4
Also it's not necessary to append to a list.
When have done if check in function then it's not needed to add != False: outside.
def is_prime_v1(n):
    if n == 1:
        return False
    for d in range(2, n):
        if n % d == 0:
            return False
    return True

for i in range(1, 21):
    if is_prime_v1(i):
        print(i)
Output:
2 3 5 7 11 13 17 19
Frankduc and BashBedlam like this post
Reply
#5
I agree with you. My goal was to print the result with and without a list.
At first i wanted to print without a list but ended up with False and True. Removing false or true get you a none.
Than i returned n to only get the primes. But true is in output. I tried for fun Ruby language. I like the idea to not have to return something (return is automatic). In python you have to return otherwise nothing comes out.

In the end your solution is what i was looking for. Just that was enough:

for n in range(1,21):
  if is_prime_v1(n):
   print(n)
     
print(prime)  
Again a logic problem i suppose.
Reply
#6
Frankduc Wrote:Wonder what is the principle idea behind the scene to be force to create a new variable to escape the indent.
Your design is wrong from the start because the role of function is_prime_v1() is not well defined. It tells whether n is prime by returning a boolean, and at the same time, it appends items to the prime list and returns the value of n. These are too many tasks for a single function.
def is_prime_v1(n):
    """Return a boolean indicating if integer n is prime"""
    if n == 1:
     return False
     
    for d in range(2, n):
        if n % d == 0:
            return False
    return True

prime = []
for n in range(1,21):
  if is_prime_v1(n):
    prime.append(n)

print(prime)
Output:
[2, 3, 5, 7, 11, 13, 17, 19]
Frankduc and BashBedlam like this post
Reply
#7
It maybe the right way to do this. The difference in compiling is small.
My version: Time required 0.00012230873107910156
Yours: 0.0001380443572998047
That if i timed it correctly with an online compiler.
Reply
#8
Worry about being correct first, then worry about speed. Your design was incorrect. It did not create a list you wanted. This has nothing to do with indenting and all to do with writing the wrong code.
Reply
#9
Got influenced by this code:

def primes(n): # Sieve of Eratosthenes
    prime, sieve = [], set()
    for q in range(2, n+1):
        if q not in sieve:
            prime.append(q)
            sieve.update(range(q*q, n+1, q))
    return prime

print(primes(20))
list and set are inside the function. I learned in c# that list must be close the for loop just above. But it depends what return you are expecting. In this case its a function.
Reply
#10
In the Sieve of Eratosthenes example the prime list and sieve set are generated fresh each time the function is called. The user wants a list of prime numbers up to and including "n". The algorithm depends on generating a set of non-prime numbers. But even if you don't want a list there are lots of things you can do with a list. Sometimes creating a list may be the most efficient way to accomplish your goal.

Looking at your code it is unclear what you want to accomplish. If you just want to print the prime number in the range 0..20 the Sieve of Eratosthenes may be the most efficient way to do that.
def primes(n): # Sieve of Eratosthenes
    prime, sieve = [], set()
    for q in range(2, n+1):
        if q not in sieve:
            prime.append(q)
            sieve.update(range(q*q, n+1, q))
    return prime
 
for prime in primes(20): 
    print(prime)  # Because you want to print them one per line.
The code is very efficient because it doesn't do any division or much math at all, far more efficient than using the modulo operator. This would be seen if n=1000000 instead of 20.

If you really hate the idea of having a list, even as a temporary holder for your values, you could rewrite this as a generator.
def primes(n): # Sieve of Eratosthenes
    sieve = set()
    for q in range(2, n+1):
        if q not in sieve:
            yield q
            sieve.update(range(q*q, n+1, q))
    return prime

for prime in primes(20):
    print(prime)
Now primes() returns a number, not a list of numbers. It doesn't make much sense writing something like Sieve of Eratosthenes as a generator. The algorithm needs an ending point and making the ending point arbitrarily large makes the algorithm run very slow. But for many kinds of calculations or operations a generator is the way to go. You don't have to wait for it to compute every result, and it doesn't use a lot of storage to save results.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  use of escape character in re.sub and find WJSwan 1 916 Feb-16-2023, 05:19 PM
Last Post: Larz60+
  add Escape charcters in string GrahamL 3 1,176 Jan-20-2022, 01:15 PM
Last Post: GrahamL
  Escape Single quotation between each content tag usman 3 2,811 May-02-2021, 03:32 PM
Last Post: snippsat
  DIY Escape Room for fun StannemanPython 1 2,317 Feb-17-2021, 10:53 PM
Last Post: maurom82
  How to escape OrderedDict as an argument? Mark17 2 2,029 Dec-23-2020, 06:47 PM
Last Post: Mark17
  help for escape sequences NewPi 1 2,039 Dec-11-2019, 11:22 PM
Last Post: ichabod801
  escape single quote deep_logic 1 1,808 Sep-10-2019, 08:05 PM
Last Post: SheeppOSU
  The use of escape char \ hishamzero1 2 2,380 Aug-12-2019, 10:20 PM
Last Post: hishamzero1
  Escape sequences display in python Uchikago 1 2,436 Jun-27-2019, 03:25 PM
Last Post: Gribouillis
  Python 3 escape codes oldDog 1 2,600 Sep-15-2018, 10:12 AM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020