I’m trying to check for a palindrome with Python. The code I have is very for
-loop intensive.
And it seems to me the biggest mistake people do when going from C to Python is trying to implement C logic using Python, which makes things run slowly, and it’s just not making the most of the language.
I see on this website. Search for «C-style for», that Python doesn’t have C-style for loops. Might be outdated, but I interpret it to mean Python has its own methods for this.
I’ve tried looking around, I can’t find much up to date (Python 3) advice for this. How can I solve a palindrome challenge in Python, without using the for loop?
I’ve done this in C in class, but I want to do it in Python, on a personal basis. The problem is from the Euler Project, great site By the way,.
def isPalindrome(n):
lst = [int(n) for n in str(n)]
l=len(lst)
if l==0 || l==1:
return True
elif len(lst)%2==0:
for k in range (l)
#####
else:
while (k<=((l-1)/2)):
if (list[]):
#####
for i in range (999, 100, -1):
for j in range (999,100, -1):
if isPalindrome(i*j):
print(i*j)
break
I’m missing a lot of code here. The five hashes are just reminders for myself.
Concrete questions:
-
In C, I would make a for loop comparing index 0 to index max, and then index 0+1 with max-1, until something something. How to best do this in Python?
-
My for loop (in in range (999, 100, -1), is this a bad way to do it in Python?
-
Does anybody have any good advice, or good websites, or resources for people in my position? I’m not a programmer, I don’t aspire to be one, I just want to learn enough so that when I write my bachelor’s degree thesis (electrical engineering), I don’t have to simultaneously LEARN an applicable programming language while trying to obtain good results in the project. «How to go from basic C to great application of Python», that sort of thing.
-
Any specific bits of code to make a great solution to this problem would also be appreciated, I need to learn good algorithms.. I am envisioning 3 situations. If the value is zero or single digit, if it is of odd length, and if it is of even length. I was planning to write for loops…
PS: The problem is: Find the highest value product of two 3 digit integers that is also a palindrome.
Автор оригинала: Team Python Pool.
Один из самых простых и часто задаваемых вопросов на интервью – проверить, является ли строка палиндромом или нет, используя Python.
Палиндром – это строка или число, которое, если повернуть вспять, равно исходному значению. Например, если мы перевернем строку MALAYALAM, мы получим обратно исходную строку. Кроме того, если мы перевернем число 12321, мы получим 12321 обратно. Они известны как палиндромы.
В этой статье мы узнаем, как проверить, является ли строка или число палиндромом или нет, разными способами. В дополнение к этому мы решим некоторые вопросы болельщиков, которые обычно задаются на соревнованиях и интервью.
В этой статье мы узнаем, как проверить, является ли строка или число палиндромом, различными способами. В дополнение к этому мы решим несколько интересных вопросов, которые обычно задаются в конкурсах и интервью.
- Проверьте Палиндром с помощью нарезки (slicing) в Python
- Проверьте Палиндром с помощью функции reversed() В Python
- Проверьте Палиндром с помощью цикла while в Python
- Проверка того, является ли число палиндромом в Python с помощью цикла
- Проверка того, является ли фраза палиндромом в Python
- Как найти самую длинную палиндромную подстроку в строке
1. Проверьте Palindrome с помощью нарезки в Python
Мы можем использовать концепцию нарезки, чтобы перевернуть строку, а затем мы можем проверить, равна ли перевернутая строка исходной строке или нет.
def check_palindrome(string): # transversing the string from last to first reversed_string = string[::-1] if string == reversed_string: print(string, "is a palindrome") else: print(string, "is not a Palindrome") if name=='main': check_palindrome("RADAR") check_palindrome("PythonPool")
Output- RADAR is a palindrome PythonPool is not a Palindrome
Вышеприведенный метод прост в использовании, а также хорош, и вы можете использовать его на соревнованиях, но люди обычно не предпочитают использовать его в интервью. Этот метод настолько прост, и люди предпочитают кодировать с нуля, чтобы сделать такую программу, чтобы показать свои навыки. Мы также рассмотрим этот подход в следующем разделе.
2. Проверьте Палиндром с помощью цикла в Python
def is_palindrome(string): reversed_string = "" # transversing through string from last for i in range(len(string), 0, -1): # Addind last characters of string into a new string reversed_string += string[i-1] if string == reversed_string: print("Palindrome") else: print("Not a palindrome") if __name__ == __'main'__: is_palindrome("racecar") is_palindrome("Python")
Output- Palindrome Not a palindrome
3. Проверьте Палиндром С Помощью функции reversed() в Python
string="MALAYALAM" # joining characters of reversed string one by one reversed_string = ''.join(reversed(string)) if reversed_string == string: print(string," is Palindrome") else: print(string,"Not a Palindrome")
Output- MALAYALAM is Palindrome
4. Проверьте на Палиндром с помощью цикла while в Python
def check_palindrome(string): l = len(string) first = 0 last = l - 1 isPalindrome = True # ensuring that we do not iterate through more than half # of the list while first < last: # if the first character is same as last character keep # moving further if string[first] == string[last]: first = first + 1 last = last - 1 # if the characters at first and last do not match break # the loop else: isPalindrome = False break return isPalindrome if __name__ == __'main'__: isPalindrome = check_palindrome("MADAM") if isPalindrome: print("It is a palindrome ") else: print("Not a Palindrome")
Output- It is a palindrome
5. Проверка является ли число Палиндромом в Python с помощью цикла
Мы будем использовать следующую концепцию:
Число = 12321
Остаток этого числа, деленный на 10, равен:
Число% 10 = 12321% 10 = 1
Reverse_Number=Remainder=1
Затем мы разделим число на 10.
Число = Number/10 = 12321//10 = 1232
Остаток = 1232% 10 = 2
Reverse_Number=Remainder=12
Число = 1232/10 = 123
Остаток = 123% 10 = 3
Reverse_Number=Remainder=123
Число = 123/10 = 12
Остаток = 12% 10 = 2
Reverse_Number=Remainder=1232
Число = 12/10 = 1
Остаток = 1% 10 = 1
Reverse_Number=Remainder=12321
Программа:
number = 12321 reverse_number = 0 n = number # while we have not reached the end of the number while n != 0: # finding the last element of number 'n' rem = n % 10 reverse_number = reverse_number * 10 + rem n = int(n / 10) if number == reverse_number: print("Palindrome") else: print("Not a Palindrome")
Мы также можем сначала преобразовать число в строку, а затем применить любой из вышеприведенных методов, чтобы проверить, является ли это число палиндромом или нет.
number = 12321 # converting the number to string and then reversing it if str(number)[::-1] == str(number): print("Number:", number, " is a Palindrome") else: print("Number:", number, " is not a Palindrome")
Output- Number: 12321 is a Palindrome
6. Проверка того, является ли фраза палиндромом в Python
Проверка, является ли фраза палиндромом или нет, отличается от проверки, является ли слово палиндромом или нет.
Например, фраза “Too hot to hoot” является палиндромом, если игнорировать верхний регистр – нижний регистр и пробелы в символах.
def is_palindrome(string): reversed_string = "" # Removing all the spaces s = string.replace(" ","") # making the whole string in lowercase characters s = s.lower() for i in range(len(s), 0, -1): if s[i-1] >= 'a' and s[i-1] <= 'z': reversed_string += s[i - 1] if s == reversed_string: print("Palindrome") else: print("Not a palindrome") if __name__ == '__main__': is_palindrome("Too hot to hoot") is_palindrome("Python")
Output- Palindrome Not a palindrome
Есть и другие типы палиндромов, например: “Is it crazy how saying sentences backward creates backward sentences saying how crazy it is”. Он отличается от других палиндромов, которые мы обсуждали до сих пор, потому что здесь, если мы перевернем символы, это не палиндром. Но если мы перевернем его слово за словом, то это будет палиндром.
Программа:
string = 'Is it crazy how saying sentences backwards creates backwards sentences saying how crazy it is' string1 = string.lower() string1 = string.replace(" ", "") new_string = "" # Wherever there is any space make a list element list1 = string1.split(" ") # join the list into string starting from the last reverse = "".join(list1[::-1]) reverse_string = "" for i in reverse: # adding only characters in the new string if i >= 'a' and i <= 'z': reverse_string+=i for i in string1: if i >= 'a' and i <= 'z': new_string += i if new_string == reverse_string: print(string, ":Palindrome") else: print(string, ":Not a Palindrome")
Output- Is it crazy how saying sentences backward creates backward sentences saying how crazy it is: Palindrome
7. Как найти самую длинную палиндромную подстроку в строке
Очень распространенный и интересный вопрос о палиндромах состоит в том, чтобы найти самую длинную подстроку, которая является палиндромом из строки, которая может быть или не быть палиндромом. Я предлагаю вам попробовать это самостоятельно один раз, а затем посмотреть на решение ниже. Есть много способов решить эту проблему. Мы пойдем самым простым путём, который сможем легко понять.
m = "" s = 'babad' for i in range(len(s)): # iterating through the string from the last for j in range(len(s), i, -1): # ensuring that we do not iterate through more than half of # the string if len(m) >= j-i: break elif s[i:j] == s[i:j][::-1]: m = s[i:j] print(m)
Алгоритмическая сложность для приведенной выше программы равна O(n^2), так как у нас есть цикл for внутри другого цикла for.
Читайте также:
- Как преобразовать строку в нижний регистр
- Как вычислить Квадратный корень
- Пользовательский ввод | Функция input() | Ввод с клавиатуры
Вывод
Мы изучили, что такое палиндром, как проверить, является ли строка или число палиндромом. Мы также рассмотрели некоторые распространенные вопросы интервью, такие как проверка фразы, если она является палиндромом, и поиск самой длинной подстроки, которая является палиндромом в Python. Я надеюсь, что вы попробуете каждое решение.
Given a string, write a python function to check if it is palindrome or not. A string is said to be a palindrome if the reverse of the string is the same as the string. For example, “radar” is a palindrome, but “radix” is not a palindrome.
Examples:
Input : malayalam Output : Yes Input : geeks Output : No
Method #1
- Find reverse of the string
- Check if reverse and original are same or not.
Python
def
isPalindrome(s):
return
s
=
=
s[::
-
1
]
s
=
"malayalam"
ans
=
isPalindrome(s)
if
ans:
print
(
"Yes"
)
else
:
print
(
"No"
)
Time complexity: O(n)
Auxiliary Space: O(1)
Iterative Method: This method is contributed by Shariq Raza. Run a loop from starting to length/2 and check the first character to the last character of the string and second to second last one and so on …. If any character mismatches, the string wouldn’t be a palindrome.
Below is the implementation of above approach:
Python
def
isPalindrome(
str
):
for
i
in
range
(
0
,
int
(
len
(
str
)
/
2
)):
if
str
[i] !
=
str
[
len
(
str
)
-
i
-
1
]:
return
False
return
True
s
=
"malayalam"
ans
=
isPalindrome(s)
if
(ans):
print
(
"Yes"
)
else
:
print
(
"No"
)
Time complexity: O(n)
Auxiliary Space: O(1)
Method using the inbuilt function to reverse a string:
In this method, the predefined function ‘ ‘.join(reversed(string)) is used to reverse string.
Below is the implementation of the above approach:
Python
def
isPalindrome(s):
rev
=
''.join(
reversed
(s))
if
(s
=
=
rev):
return
True
return
False
s
=
"malayalam"
ans
=
isPalindrome(s)
if
(ans):
print
(
"Yes"
)
else
:
print
(
"No"
)
Time complexity: O(n)
Auxiliary Space: O(n)
Method using one extra variable: In this method, the user takes a character of string one by one and store it in an empty variable. After storing all the characters user will compare both the string and check whether it is palindrome or not.
Python
x
=
"malayalam"
w
=
""
for
i
in
x:
w
=
i
+
w
if
(x
=
=
w):
print
(
"Yes"
)
else
:
print
(
"No"
)
Time complexity: O(n)
Auxiliary Space: O(n)
Method using flag: In this method, the user compares each character from starting and ending in a for loop and if the character does not match then it will change the status of the flag. Then it will check the status of the flag and accordingly and print whether it is a palindrome or not.
Python
st
=
'malayalam'
j
=
-
1
flag
=
0
for
i
in
st:
if
i !
=
st[j]:
flag
=
1
break
j
=
j
-
1
if
flag
=
=
1
:
print
(
"NO"
)
else
:
print
(
"Yes"
)
Time complexity: O(n)
Auxiliary Space: O(1)
Method using recursion:
This method compares the first and the last element of the string and gives the rest of the substring to a recursive call to itself.
Python3
def
isPalindrome(s):
s
=
s.lower()
l
=
len
(s)
if
l <
2
:
return
True
elif
s[
0
]
=
=
s[l
-
1
]:
return
isPalindrome(s[
1
: l
-
1
])
else
:
return
False
s
=
"MalaYaLam"
ans
=
isPalindrome(s)
if
ans:
print
(
"Yes"
)
else
:
print
(
"No"
)
Time complexity: O(n)
Auxiliary Space: O(n)
Method : Using extend() and reverse() methods
Python3
def
isPalindrome(s):
x
=
list
(s)
y
=
[]
y.extend(x)
x.reverse()
if
(x
=
=
y):
return
True
return
False
s
=
"malayalam"
ans
=
isPalindrome(s)
if
ans:
print
(
"Yes"
)
else
:
print
(
"No"
)
Time complexity: O(n) where n is the length of a given string
Auxiliary space: O(n)
This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Last Updated :
16 Feb, 2023
Like Article
Save Article
What is a Palindrome?
A palindrome is a word, number, or any string of characters which reads the same backward as it reads forward.
You may have to check whether a number is a palindrome or not in everyday programming and competitive programming. It is straightforward to reverse a number and check it. However, you need to perform the one-liner logic to check readability and reduce the lines of code. From the following examples, you can understand what a palindrome number in python is.
Few examples: detartrated, 1567651, 02/02/2020, Malayalam
So this article shows you various ways you can write a program to check whether a given input is a palindrome or not, using Python.
Method 1:
The most naïve solution which comes to mind is to reverse the number and check if it equals the input number. It can be done as follows:
number = int(input());
reverse = 0
while number > 0:
digit = number % 10
reverse = reverse * 10 + digit
number = number // 10
if number==reverse:
print(“it is a palindrome!”)
else:
print(“it is not a palindrome!”)
However, this compromises the readability of the code and has more lines of code than required. Checkout our online data science course to learn more.
Here’s a short and sweet way to check a number using just one line.
Method 2:
The trick is to take the input number as a str data type instead of int. Then you can use the [::-1] slicing technique to obtain the reverse of a string and check for equality in the if statement itself.
A slicing method helps you determine the reverse. You can also use the built-in ‘’.join(reversed()). There are several other ways to reverse a string, but the following section discusses a simple palindrome number program in python.
This program compares the reversed string with the original string. It returns “True” if both the strings are equal, else it returns “False”.
number = input()
if number == number[::-1]:
print(“it is a palindrome!”)
else:
print(“it is not a palindrome!”)
Method 3:
This is a recursive method to check if an array is a palindrome or not.
def isPalindrome(numbers, start, end):
if start >= end:
return True
if numbers[start] == numbers[end]:
return isPalindrome(numbers, start + 1, end – 1)
else:
return False
numbers= list(map(int, input().split()))
n=len(numbers)
if isPalindrome(numbers, 0, n-1):
print(“it is a palindrome!”)
else:
print(“it is not a palindrome!”)
The isPalindrome function checks whether the first and last array elements are same or not. If not, the function immediately returns False. Otherwise it recursively checks for the next extreme elements till the two pointers meet in the middle.
Read: Python Project Ideas & Topics
How does Palindrome work in Python?
The function’s argument is considered and its reverse is determined. This is then stored in a separate variable. The length technique helps determine the reverse.
This step determines the variable’s length, and a manual reverse is employed on top of the length.
The actual variable and variable with reverse stored are compared to determine whether they contain the same value. palindrome number in python
The “True” value is returned from the function if both values are matched. The “False” value is returned from the function if both the values don’t match.
The message “The string is a palindrome” is printed when the value is “True”. The message “The string is not a palindrome” is printed when the value is “False”.
Methods to find Palindrome in Python:
1) Without determining the reverse of the string:
It constantly compares the characters present at the first and last index of the string. The comparison continues until they are unequal.
The following section discusses this method with the help of two examples.
Example-1:
String value “malayalam”:
It compares the first and last characters and they are equal. It then compares the second and second last characters and they are equal. The process in this palindrome number program in python continues until all characters are checked this way. Hence, the string is a palindrome.
Example-2:
String value “shops”:
Only the first and last characters are equal. When the second and second last characters are compared, they are found unequal. So, it is not a palindrome.
You can implement this idea through two pointers or recursion. Let’s first implement using pointers. You begin with the start pointer 0 and the end pointer at the last index. The comparison goes on and if characters are equal, the start pointer is incremented and the end pointer is decremented.
The question that arises in this palindrome number python is when to return False. There is no need to look for subsequent indexes, so “False” is returned if the characters for any set of pointers are unequal.
When to return “True” in the palindrome number program in python? If a string is a Palindrome, “True” is returned when both the pointers are equal, or the start pointer surpasses the end pointer and returns true.
For Loop to check for Palindrome in Python:
You can use the “For” loop in Python to loop over a string in reverse order. Let’s check how to use the “For” loop to check for the palindrome number program in python.
s = ‘Poor Dan is in a droop’
def palindrome(s):
s = s.lower().replace(‘ ‘, ”)
reversed_string = ”
for i in range(len(s), 0, -1):
reversed_string += s[i-1]
return a_string == reversed_string
print(palindrome(s))
# Returns: True
The output of the above program shows that the entered string is Palindrome.
checkPalindrome() method to check for Palindrome in Python:
The checkPalindrome()is a user-defined method that accepts a value and returns a value if the reciprocal equals the element itself. So, we accepted the number provided by the user as a parameter to the checkPalindrome()method. The return variable is therefore initialized with the variable “chck”. When comparing the values of the variable “chck”, if it contains 1, it means the given value is a palindrome. Otherwise, the entered value is not a palindrome.
For example, if the entered number is “987569”. After reversing the number, it is compared to the originally entered number. But they both are not equal. So, “987569” is not a palindrome number.
reversed() method to check for Palindrome in Python:
The reversed() function in Python determines whether the entered value or string is a palindrome or not. It accepts a series of characters and returns the inverse iterator. Instead of the list catalog [::-1], reversed() method is used to inverse the series of values within the string. The real and inverted string is compared elements by elements. Finally, it determines whether the number is palindrome or not.
Code for the reversed() method to check for palindrome number python:
w = input()
if str(w) = = “” . join (reversed(w))
print (“It is a palindrome”)
else
print (“It is not a palindrome)
For example, you can use the reversed() method to check if the string “nayan” is a palindrome or not. Firstly, the “.join (reversed () function” helps to analyze the inverse of the real string. The “==” equation operator is used to compare both the real string and the inverse string. The message “It is a palindrome” is printed if the real string and the reverse string are equal.
The fastest way to check if a string is Palindrome or not in Python:
The fastest way to check for a palindrome number python is string indexing. It can work up to 70 times faster than a “For” loop.
Top Data Science Skills to Learn
Common coding interview questions related to palindromes
#1 Longest palindromic Substring
Given only one string as an input, you have to return the length of the longest palindromic substring in the string.
Eg:
Input: ‘acbcbabcc’
Output: 5 (‘cbabc’)
Approach:
If we try to relate this to one of the most common problems of DP, the longest common substring, here the difference is that we are given only one input string whereas LCS uses two strings. Since we know a palindrome is exactly equal to its reverse, we can make the second string as the reverse of our given input.
Now this becomes exactly the same as finding LCS.
def LCSubstr(A, B, m, n):
LCSub = [[0 for i in range(n+1)] for j in range(m+1)]
ans = 0
for i in range(m+1):
for j in range(n+1):
if (i == 0 or j == 0):
LCSub[i][j] = 0
elif A[i-1] == B[j-1]:
LCSub[i][j] = 1 + LCSub[i-1][j-1]
ans = max(ans, LCSub[i][j])
else:
LCSub[i][j] = 0
return ans
str1 = input()
str2 = str1[::-1]
m = len(str1)
n = len(str2)
print(‘Length of longest palindromic substring = ‘, LCSubstring(str1, str2, m, n))
So for the above input, we obtain the two strings as
‘acbcbabcc’ and
‘ccbabcbca’
The longest common substring becomes ‘cbabc’ which is of length 5.
Read our popular Data Science Articles
#2 Check if an Anagram of a String is a Palindrome
Given a string as an input, you have to check if any anagram of the string can be a palindrome or not and return yes/no accordingly.
Eg:
Input: ‘pythonpython’
Output: Yes
(while the string itself is not a palindrome, a possible anagram ‘pythonnohtyp’ does form a palindrome)
Input: ‘harrypotter’
Output: No
Approach:
If you notice carefully, whenever we have a palindrome string of even length, all the characters in the first half are repeated in the second half. This means all characters present in the string occur an even number of times.
When the length is odd, all characters to the left of the middle element (not inclusive) occur the same number of times in the right side of the middle element. This means there is only one character which occurs an odd number of times (middle element) and all the others occur even number of times.
upGrad’s Exclusive Data Science Webinar for you –
ODE Thought Leadership Presentation
Using this logic, we can store the count of the characters in the string in a hash and check for these constraints to get the required answer.
CHAR_RANGE = 256
str1 = input()
freq = [0 for i in range(CHAR_RANGE)]
for i in str1:
freq[ord(i)] += 1 #ord(x) gives the unicode value of x
num_odds = 0
for i in range(CHAR_RANGE):
if freq[i] & 1:
num_odds += 1
if (num_odds > 1):
print(“Yes”)
else:
print(“No”)
Our learners also read: Top Python Courses for Free
Top Data Science Skills to Learn
Conclusion
In conclusion, the palindrome problems are very common and interesting. They are useful to solve various mathematical puzzles and competitive programming questions.
If you are curious to learn about data science, check out IIIT-B & upGrad’s Executive PG Programme in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.
What is the time complexity of the Palindrome program?
The number of elementary operations done by the method is often used to estimate time complexity, assuming that each elementary process takes a set amount of time to complete. The time complexity of determining whether or not a number is a palindrome is O(log10 (n)). When we check for the values to be a palindrome, we divide the number or value by ten in each iteration. As a result, the temporal complexity is equal to the number of digits in a number.
How is / different from // operator in Python?
When we use the divide operator, i.e., a single slash (/) in Python, the compiler simply divides the two values on the right and left sides of the slash. But when we use double slash(//), i.e., floor division, we ask the compiler to carry out the typical division process, but the result it yields is the biggest integer possible close to the answer. This integer is either less than or equal to the result of normal division.
What is the entry-level salary of a Python Developer?
It’s a well-known fact that Python is widely used in most industries and companies, making Python the second-highest-paid computing language. Python is also the favorite programming language amongst students and professionals because it is easy to learn and is highly flexible. The entry-level salary of a Python Developer in India is around INR 4,27,293 per annum on average. Professionals learning Python have a lot of scope as Python is also used in other fields such as Data Science and Machine Learning.
Want to share this article?
Prepare for a Career of the Future
Be a Certified Data Scientist — Advanced Certificate Programme in Data Science
Learn More
Палиндром в Python – это число или буква, которые остаются неизменными, даже если число и буквы перевернуты.
Например:
121, 11, 414, 1221, 74747 – числа палиндрома.
MOM, DAD, MADAM, REFER – это буквы палиндрома.
JAVATPOINT, PROGRAM, JAVA – это не буквы палиндрома.
Алгоритм палиндрома
- Прочтите цифру или букву.
- Сохраните букву или цифру во временной переменной.
- Переверните букву или цифру.
- Сравните временную переменную с обратной буквой или цифрой.
- Если обе буквы или цифры совпадают, выведите «эта строка / число является палиндромом».
- Иначе напишите «эта строка / число не является палиндромом».
Примеры программ палиндрома на Python:
Программа 1: строка палиндрома
str = 'JaVaJ' str = str.casefold() # This string is reverse. rev = reversed(str) if list(str) == list(rev): print("PALINDROME !") else: print("NOT PALINDROME !")
Выход:
PALINDROME !
Программа 2: строчная программа палиндрома
string=input(("Enter a letter:")) if(string==string[::-1]): print("The letter is a palindrome") else: print("The letter is not a palindrome")
Выход:
Enter a letter: javatpoint The letter is not a palindrome Enter a letter: MADAM The letter is a palindrome
Программа 3: числовая программа-палиндром с использованием цикла while
Num = int(input("Enter a value:")) Temp = num Rev = 0 while(num > 0): dig = num % 10 rev = rev * 10 + dig num = num // 10 if(temp == rev): print("This value is a palindrome number!") else: print("This value is not a palindrome number!")
Выход:
Enter the value: 2551 This value is not a palindrome number! Enter the value: 1221 This value is a palindrome number!
Изучаю Python вместе с вами, читаю, собираю и записываю информацию опытных программистов.