user2172079
user2172079

Reputation: 11

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!

Upvotes: 0

Views: 5755

Answers (2)

Syed Albiz
Syed Albiz

Reputation: 91

You're returning inside the for loop before you have a chance to increment the counter You also don't need that empty 'else: pass' block as it does nothing.

A correct solution will return the counter at the end of the function after the loop terminates.

Something like this will work:

count = 0
for i in range(171, 115000):
    if str(i) == str(i)[::-1]:
        count += 1
return count

Note a few style changes: - 4-space indentation - no extraneous newlines - no unnecessary coercion of i from 'True/False' to a number (which is what you get in your code when you do i = str(i) == str(i)[::-1])

Not directly related to your question but following python conventional style will help make your code more readable and easier for others to understand and help you with.

Lastly, just as n extra tidbit, you can also accomplish this task with a list comprehension:

sum([1 for i in range(171, 115000) if str(i) == str(i)[::-1]])

I personally find it more concise/easier to understand than the loop counter variation.

Upvotes: 0

jamylak
jamylak

Reputation: 133624

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))

Upvotes: 2

Related Questions