The question is: print out all numbers from 1 to 1000 that satisfy the two conditions:
- Those are prime numbers
- The numbers after being reversed are also prime numbers.
e.g., 13 satisfies (as 13 and 31 are prime numbers), but 19 does not satisfy (19 is a prime number, while 91 is not).
My codes:
def prime(n):
if n<2:
return False
for i in range(1, n):
if n%i == 0:
return False
else:
return True
def reverse(n):
List = []
while n>0:
List.append(n%10)
n = n//10
string = [str(integer) for integer in List]
a_string = "".join(string)
result = int(a_string)
print(result)
L = []
for i in range (1, 1000):
if prime(i) == prime(reverse(i)) == True:
L.append(i)
print(L)
Mine seems to contain some errors as the outcome is not as expected, either it shows none or still shows 19 in the list.
Thank you in advance!
>Solution :
First your prime method is wrong, because the loops starts at 1, and every numbre satisfies n%1 == 0 , it needs to starts at 2
def prime(n):
if n < 2:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
Then your reverse method returns nothing so reverse(5) gives None, you have tried it manually.
def reverse(n):
values = []
while n > 0:
values.append(n % 10)
n = n // 10
return int("".join(map(str, values)))
Then simplify the condition to be
for i in range(1, 20):
if prime(i) and prime(reverse(i)):
L.append(i)
The reverse process can be done with string also, and so short that it can be inlined
L = []
for i in range(1, 20):
if prime(i) and prime(int(str(i)[::-1])):
L.append(i)