Search code examples
pythonfor-looppython-3.xpalindrome

counting the number of palindromes in a range in python


I'm sort of new to python. I'm trying to go through a specific range of numbers and have python count all the palindromes in it and return them to me (total number count, not their sum). So it would count all the integers in this range and return it to me as one number.

I keep getting an invalid syntax error and I don't know what to change. Here is what I have so far:

import math

def ispal(n):
    return str(n) == str(n)[::-1]

But this is basically just what we did in class.

My range of of numbers is from 171 to 115000 and I want to go through the entire range in between and including those 2 numbers and have python tell me how many numbers are palindromes. The problem is I don't know how to fit in the for loop.

I started with:

def count_pal(n):  
   count = 0  
   for i in range(n):  
       if i = str(n) == str(n)[::-1]:
           return:  
           count =+ i   
   else:
       pass

But I don't know how to put the 2 together. I have python 3.2. Can anyone please help me out? Thank you!


Solution

  • def num_palindromes(start, end):
        count = 0
        for i in range(start, end + 1):
            if str(i) == str(i)[::-1]:
                count += 1
        return count
    

    Or as a one liner

    def num_palindromes(start, end):
        return sum(str(i) == str(i)[::-1] for i in range(start, end + 1))