1

I just write this algorithm that searches for prime palindromic (both binary and decimal) number, but I got an error:

Traceback (most recent call last):
  File "python", line 25, in <module>
  File "python", line 10, in isPalindromic
TypeError: not all arguments converted during string formatting"

I can't understand where is my fault. Also I'm not sure if this works, but for me (I'm new in programming) sounds logical.

import math
def isPalindromic():

    n = 10

    while True:

        for i in range(3, int(math.sqrt(n)) + 1):

            if n % i != 0:
                n = str(n)
                new_number = n[::-1]

                if n == new_number:

                    n = int(n)
                    binary = str(bin(n)[2:])
                    binary_new = binary[::-1]
                    if binary == binary_new:
                        return n 

        n = int(n)
        n = n + 1 

a = isPalindromic()
Paul Draper
  • 78,542
  • 46
  • 206
  • 285
Georgi Stoyanov
  • 469
  • 1
  • 5
  • 24
  • Is the indentation now correct? Because it looks like `n = int(n)` is now outside the `for` loop, which would explain why `n` is a string (and causing `n % i` to fail). – Martijn Pieters Nov 17 '13 at 10:51

3 Answers3

4

Add n = int(n) inside for loop for the case when n != new_number. As in this case n = str(n) and hence is string, so n % i is treated as string formatting operation. And since n contains no format derectives, you got your error.

alko
  • 46,136
  • 12
  • 94
  • 102
4

Sometimes n is an int, sometime it is a string. When it is a string, % is the formatting operator.

Using one variable for both is bound to get you in trouble.

Also, your code can be cleaned up a lot.

import math

def is_palindrome(s):
    return s == s[::-1]

def is_prime_dual_palindromic(n):
    return all(n % i for i in range(2, int(math.sqrt(n)) + 1)) \
        and is_palindrome(str(n))                              \
        and is_palindrome(bin(n)[2:])

a = is_prime_dual_palindromic(10)
Paul Draper
  • 78,542
  • 46
  • 206
  • 285
2

Just change this line:

if n % i != 0:

To this:

if int(n) % i != 0:

The problem is you are using the % operator on a string, not an int. Which means instead of getting the modulus operator, you are getting string formatting operator. Check here for more information on the % in Python.

Community
  • 1
  • 1
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131