I am currently enrolled in a Python programming course and last week we got a homework problem which was to Develop a program to generate all prime numbers less or equal to n whose mirror is also prime, I can't see where I am going wrong, please help!
import math
def mirror_prime(n):
answer = True
# Test 0 and 1
if n==0 or n==1:
answer = False
# End if
# Test even numbers
if n != 2 and n%2==0:
answer= False
# End if
# Test if there is a proper odd divisor
for d in range (3, int(math.sqrt(n))+1, 2):
if n%d==0:
answer=False
# End if
# End for
#Reverse n
mirror_n = int(str(n)[::-1])
mirror_answer = True
# Test 0 and 1
if mirror_n==0 or mirror_n==1:
mirror_answer = False
# End if
def mirror_prime_generator(n):
for i in range(3, n+1):
print (mirror_prime(i))
I am expecting to get a list of all prime numbers whose mirror is also prime less or equal to n
The result i get when i put mirror_prime_generator(n) into the shell, it justs prints none however many times n is, so if n is 23 it will print none 23 times
There were still some bugs. The indentation of for loops was wrong (they were inside the if) and you sometimes used n instead of mirror_n.
Here's a working code with the least amount of change:
import math
def mirror_prime(n):
answer = True
# Test 0 and 1
if n==0 or n==1:
answer = False
# End if
# Test even numbers
if n != 2 and n%2==0:
answer= False
# End if
# Test if there is a proper odd divisor
for d in range (3, int(math.sqrt(n))+1, 2):
if n%d==0:
answer=False
# End if
# End for
#Reverse n
mirror_n = int(str(n)[::-1])
mirror_answer = True
# Test 0 and 1
if mirror_n==0 or mirror_n==1:
mirror_answer = False
# End if
# Test even numbers
if mirror_n != 2 and mirror_n%2==0:
mirror_answer= False
# End if
# Test if there is a proper odd divisor
for d in range (3, int(math.sqrt(mirror_n))+1, 2):
if mirror_n%d==0:
mirror_answer=False
# End if
# End for
if answer and mirror_answer==True:
return n, mirror_n
def mirror_prime_generator(n):
for i in range(3, n+1):
if mirror_prime(i):
print(i)
mirror_prime_generator(100)
# 3
# 5
# 7
# 11
# 13
# 17
# 31
# 37
# 71
# 73
# 79
# 97
You should try to avoid using duplicate code. The test for n and mirror_n is exactly the same, so you could put it inside a function:
def is_prime(n):
if n == 2:
return True
if n < 2 or n % 2 == 0:
return False
for d in range(3, int(n**0.5) + 1, 2):
if n % d == 0:
return False
return True
def is_mirror_prime(n):
mirror_n = int(str(n)[::-1])
return mirror_n != n and is_prime(n) and is_prime(mirror_n)
print([n for n in range(1000) if is_mirror_prime(n)])
# [13, 17, 31, 37, 71, 73, 79, 97, 107, 113, 149, 157, 167, 179, 199, 311, 337, 347, 359, 389, 701, 709, 733, 739, 743, 751, 761, 769, 907, 937, 941, 953, 967, 971, 983, 991]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With