palindrome_tutorial.py

Created by 546f6d

Created on January 24, 2025

1.19 KB

fff


def reverse_string(string):
    reversed_string = ""
    for character in string:
        reversed_string = character + reversed_string
    return reversed_string

# Function to check if a number is a palindrome
def is_palindrome(number):
    str_number = str(number)
    return str_number == reverse_string(str_number)

def find_palindrome(target: int, display_output: bool = False):
    count = 0
    number = 0
    
    while count < target:
        if is_palindrome(number):
            count += 1
            if display_output:
                print(str(count) + ": " + str(number))
        number += 1
    return number - 1

# -------

print("")

while True:
    try:
        palindrome_target = int(input("Which palindrome number\nwould you like to find? "))
        break
    except ValueError:
        print("\nOops! That was not a\nvalid number. Try again...\n")

print("")

a = input("Would you like to display\neach palindrome number\nfound? (y/n default=n): ")
if a == "y":
    output = True
else:
    output = False

palindrome = find_palindrome(palindrome_target, output)

# Display the result
print("\nThe", str(palindrome_target) + "th palindrome number\nis:", palindrome)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.