I am new to coding and I am having a hard understanding the below code which prints all the prime numbers below 10.
N = 10
primes = []
for n in range(2,N+1):
for p in primes:
if n % p == 0: break
else:
primes.append(n)
print(primes)
My question is- what is the value of p during the first iteration? Isn't it 0? If so, n%p is always 0 right? Please help me understand.
A for..in loop over an empty list basically does nothing; it says "for each element in this list, do something", and since there is nothing in the list, it does nothing. So on the first iteration of the outer loop, the for p in primes does nothing at all, and the else clause is invoked.
On subsequent iterations there is something in primes, so the loop will get invoked and p will be populated with values.
The else clause of a for..in loop will be executed at the end of the loop, unless the loop is interrupted by break. That's exactly what is happening on your code: if the loop finds a divisible number, it breaks the loop and nothing happens, otherwise the number will get added to primes.
The algorithm in a nutshell is: for numbers from 2…10, if the number is not a multiple of an already discovered prime, it's a prime.
Related
I wrote a code in python. While changing the code, I asked myself what should be the output.
I also answered myself it should be an infinite loop. Then I ran it. But surprisingly it wasn't an infinite loop. My question is why ?
i=0
for i in range(10):
if i == 5:
i -=1
else:
print(i)
i+=1
It's very basic in python. For your information, the range() function generates a list. Here range(5) means [0,1,2,3,4].
So i iterates through the list [0,1,2,3,4] one by one. i doesn't hold the same value initialized from the beginning like a while loop condition.
for i in [0,1,2,3,4]:
if i==5:
i-=1
else:
print(i)
i+=1
Your code and this code perform similarly. The next value of i doesn't depend on the previous value of i but on the objects of the list.
Further study might be helpful for you.
range(10) produces the sequence 0,1,...,9 from which your i variable takes its values in the loop. The fact that you do i -= 1 when i == 5 won't make i to switch back and forth from 5 to 4 on and on because i is taking its values from range(10). What happens when i == 5 is that it becomes i == 4 when you do i -= 1 but at the next iteration i will take the next value from the range which would be 6, and so on until the loop ends.
Here's an infinite loop:
i=0
while i < 10:
if i == 5:
i -=1
else:
print(i)
i+=1
I am new to coding, and I am trying to write a somewhat generic prime number program. The difference with mine is that I want my program to be more efficient and only check numbers equal to, and including the square root of the number being checked, and I only want it to check previously found prime numbers. So far I have accomplished only the first criteria.
from numpy import sqrt, ceil
for a in range (3, 10000):
k=0
b=ceil(sqrt(a))
for i in range(2, int(b))
if (a%i==0):
k=k+1
if(k<=0):
print(a)
I think that I need to create a list with the number 2, run the program, and append any prime numbers that are printed to the list. However, I do not know how to:
1.) Make sure only numbers on said list are checked.
2.) Make sure only numbers through sqrt(a) are checked.
Any guidance is appreciated
You want to remember the primes that have been found, so store them in a list rather than just printing them. You mention appending primes as they are found; to do use primes.append(new_prime). Use break once you find a factor or once you pass the square root to skip to the next iteration.
primes = [2]
for tested_number in range(3, 10000, 2): #skip the evens
is_prime = True # if this is still true after testing, number is prime
for prime in primes:
if tested_number%prime == 0:
is_prime = False
break
elif prime>sqrt(tested_number): # no need to check these primes
break
if is_prime:
primes.append(tested_number)
My code is a PYTHON program that identifies if a number is prime or not. When I entered 45 however, it said that 45 was a prime, even though 45 isn't a prime number. Also, every time I run the program, it prints 'Sorry, the number you have entered is not prime.' or 'The number is indeed prime!' multiple times, instead of once. How do I make it print the output statements once and how can fix the program so that it says 45 IS NOT a prime number.
n = eval(input("Enter a number to find if that number is prime: "))
a = 2
while n > a:
if ((n % a) == 0) & (a != n):
print('Sorry, the number you have entered is not prime.')
break
else:
print('The number you have entered is indeed prime!')
Because you are printing it every time. If you want to break after finding/not finding the prime number, indent one more level for the break.
Also, this does not calculate prime numbers. It calculates if its even number.
Follow the solution here
Your code has some issues. To start with, you're never updating a, so you only ever check if the number n is even.
Once you fix that, you have two indentation problems. The first is that the break line needs to be inside the body of the if statement. Indent it more so that it's inside the if block.
The second indentation issue is more subtle. If you leave the else where it is, it will print out that the number is prime every time you test a potential factor that doesn't divide the number. That's both unhelpful (since it prints a lot) and wrong (since it says the number is prime even if it will later find a factor and say it's not prime). You can fix this by unindenting the else line so that it is lined up with the while statement. Using an else after a loop is an obscure bit of Python syntax. The body of the else only runs if the condition of the loop fails. It gets skipped if the loop exits due to a break statement.
Here's all of those necessary fixes together:
while n > a:
if ((n % a) == 0) & (a != n):
print('Sorry, the number you have entered is not prime.')
break # indent this line more!
a += 1 # increment a, so you don't keep checking 2 over and over
else: # unindent this line (and the next line too)
print('The number you have entered is indeed prime!')
There are some other things that could be improved in your code, though they aren't causing it to run incorrectly. I'd recommend using int instead of eval to parse your number, and I'd use the logical-and operator and instead of the bitwise-and operator & in the if statement (though actually you don't need either, since the a != n check is redundant, as the loop would have already ended if it was true).
I am really sorry for the vague title but I don't really know the specifics of what's happening with my code. I am currently learning Python and finding it interesting so far. I am practicing the concept of generator functions and wrote a little program that finds palindromes using a generator function.
Here is the code (Python 3.6, written in Spyder):
def ispalindrome(n):
#creates a list for storing the element of the number one by one
l=[]
#storing the digits
while n!=0:
l.append(n%10)
n=int(n/10)
#setting useful variables
i=len(l)-1
flag=False
#traversing the list and checking whether palindrome
for n in range(0,len(l)):
#this block is executed only if n is less than (len(l)-1)-n
if n<i-n:
#comparing elements
if l[n]==l[i-n]:
#flag is set to true everytime l[n] equals l[(len(l)-1)-n]
flag=True
else:
break
#if n>(len(l)-1)-n
else:
break
#returns the flag
return flag
#basic generator function that yields whenever ispalindrome() returns true
def palindromes(n=1111):
while True:
if ispalindrome(n): yield n
n+=1
#traversing through palindromes generator function
for n in palindromes():
if n>1131: break
print('{} is a palindrome'.format(n))
When ran I get this output:
1111 is a palindrome
1121 is a palindrome
1131 is a palindrome
Needless to say the output is completely wrong. I added a few prints in my code and tried to find out the issue and it looks like the program is exiting the for loop inside ispalindrome() function early. It is exiting the for-loop as soon as it encounters two digits and two ends which match, when this should not be the case. Is it because of the break keyword somehow?
I will greatly appreciate if someone can point out what am I doing wrong with this code and how should I approach this correct the issue. Thanks in advance!
I think your problem is that you've got the idea backwards.
With the current format of your code you should be assuming it IS a palindrome and breaking when you discover it is not.
Instead you are assuming it is not, then setting it to "it is" the first time you see equality. But then the next time you see inequality you merely break without setting it to false again.
If I were to code this I wouldn't bother with a flag, I would merely return "false" the moment an inequality was found.
Your logic isn't right.
By default, you think the number is not a palindrome (flag=False), and if you see a mirrored int, you set the flag to true (if l[n]==l[i-n]: flag=True).
You should do the contrary. You should set the flag to True by default, and if an item is not mirrored, return a flag to False.
As pointed out by the fellow users, my code was clearly logically in the wrong. I was never setting back flag variable to False whenever I was exiting from the for loop. So I took in account the suggestions made and changed my code.
Here is the code following my previous solution with a flag variable:
def ispalindrome(n):
#creates a list for storing the element of the number one by one
l=[]
#storing the digits
while n!=0:
l.append(n%10)
n=int(n/10)
#setting useful variables
i=len(l)-1
flag=False
#traversing the list and checking whether palindrome
for n in range(0,len(l)):
#this block is executed only if n is less than (len(l)-1)-n
if n<i-n:
#comparing elements
if l[n]==l[i-n]:
#flag is set to true everytime l[n] equals l[(len(l)-1)-n]
flag=True
else:
flag=False
break
#if n>(len(l)-1)-n
else:
break
#returns the flag
return flag
#basic generator function that yields whenever ispalindrome() returns true
def palindromes(n=1111):
while True:
if ispalindrome(n): yield n
n+=1
#traversing through palindromes generator function
for n in palindromes():
if n>2552: break
print('{} is a palindrome'.format(n))
And here is the one suggested by both Blusky and Fredman (more efficient than mine to say the least):
def ispalindrome(n):
#creates a list for storing the element of the number one by one
l=[]
#storing the digits
while n!=0:
l.append(n%10)
n=int(n/10)
#setting useful variables
i=len(l)-1
#traversing the list and checking whether palindrome
for n in range(0,len(l)):
#this block is executed only if n is less than (len(l)-1)-n
if n<i-n:
#comparing elements
if l[n]!=l[i-n]:
#flag is set to true everytime l[n] equals l[(len(l)-1)-n]
return False
#if n>(len(l)-1)-n
else:
break
#returns the flag
return True
#basic generator function that yields whenever ispalindrome() returns true
def palindromes(n=1111):
while True:
if ispalindrome(n): yield n
n+=1
#traversing through palindromes generator function
for n in palindromes():
if n>2552: break
print('{} is a palindrome'.format(n))
P.S: I am neither a professional s/w dev nor have I access to high quality courses or a mentor, that's why question boards like stackoverflow is useful for me. I know this is a dumb question and if I thoroughly checked my code again and again I might have realized the mistake, but I don't think it requires a downvote, does it?
I wrote a program in Python to generate prime numbers
here is the program
def genPrimes(n):
primes = [2] # primes generated so far
last = 3 # last number tried
while last <= n:
for p in primes:
if last % p == 0 and math.sqrt(p) <= last:
break
else:
primes.append(last)
last += 2
return primes
http://codepad.org/d33tsQyT
This program is producing a right answer. If you see the indentation for else: statement it is wrongly placed. if i try to place the else statement in if block interpreter is showing memory error. Can anyone tell why this is happening.
Thanks in advance
Maries
The else is actually attached to the for loop, and executes if the program doesn't break out of the loop. In your case, it executes if none of the primes divide into the number, so the number is prime and gets appended to the list.
See also the documentation.
It's not placed incorrectly, python is assuming you're using a for-else loop.
From the docs:
When used with a loop, the else clause has more in common with the
else clause of a try statement than it does that of if statements: a
try statement’s else clause runs when no exception occurs, and a
loop’s else clause runs when no break occurs.