Вопрос задан 02.12.2023 в 17:10. Предмет Информатика. Спрашивает Рязанов Эдик.

Python. Задача Палиндром Дано слово, состоящее только из заглавных и строчных латинских букв.

Проверьте, верно ли, что это слово читается одинаково как справа налево, так и слева направо (то есть является палиндромом), если считать заглавные и строчные буквы неразличающимися. Выведите слово YES, если слово является палиндромом, и слово NO, если не является. Решение необходимо сдать в виде функции IsPalindrome(S), возвращающей значение типа bool. При решении этой задачи нельзя пользоваться вспомогательными массивами или строками. Примеры Ввод Radar Вывод YES Ввод YES Вывод NO Код частично дан, нужно дописать недостающий кусок Код def IsPalindrome(S): (#здесь нужна недостающая часть) S = input() if IsPalindrome(S): print('YES') else: print('NO')
0 0
Перейти к ответам

Ответы на вопрос

Внимание! Ответы на вопросы дают живые люди. Они могут содержать ошибочную информацию, заблуждения, а также ответы могут быть сгенерированы нейросетями. Будьте внимательны. Если вы уверены, что ответ неверный, нажмите кнопку "Пожаловаться" под ответом.
Отвечает Герасимова Арина.

def IsPalindrome(string):

   return string == string[::-1]

S = input().lower()

if IsPalindrome(S):

   print('YES')

else:

   print('NO')

0 0
Отвечает нейросеть ChatGpt. Будьте внимательны, ответы нейросети могут содержать ошибочные или выдуманные данные.

Problem Analysis

The task requires us to determine whether a given word is a palindrome or not. A palindrome is a word that reads the same forwards and backwards, regardless of letter case. We need to implement a function `IsPalindrome(S)` that takes a word `S` as input and returns `True` if it is a palindrome, and `False` otherwise.

Plan

To solve this problem, we can use a two-pointer approach. We will start with two pointers, one at the beginning of the word and the other at the end. We will compare the characters at these positions and move the pointers towards each other until they meet in the middle. If at any point the characters are not equal, we can conclude that the word is not a palindrome.

Implementation

Here's the implementation of the `IsPalindrome` function:

```python def IsPalindrome(S): left = 0 right = len(S) - 1

while left < right: if S[left].lower() != S[right].lower(): return False left += 1 right -= 1

return True ```

Explanation

1. The function `IsPalindrome` takes a word `S` as input. 2. We initialize two pointers, `left` and `right`, pointing to the beginning and end of the word, respectively. 3. We enter a while loop that continues until the `left` pointer is less than the `right` pointer. 4. Inside the loop, we compare the characters at the `left` and `right` positions using the `lower()` method to ignore letter case. If they are not equal, we return `False` as the word is not a palindrome. 5. If the characters are equal, we move the `left` pointer one step forward and the `right` pointer one step backward. 6. After the loop ends, we return `True` as the word is a palindrome.

Testing

We can test the function using the provided examples:

```python print(IsPalindrome("Radar")) # Output: True print(IsPalindrome("YES")) # Output: False ```

Complete Code

Here's the complete code with the missing part added:

```python def IsPalindrome(S): left = 0 right = len(S) - 1

while left < right: if S[left].lower() != S[right].lower(): return False left += 1 right -= 1

return True

S = input() if IsPalindrome(S): print('YES') else: print('NO') ```

This code will take input from the user and check if the input word is a palindrome or not, printing "YES" or "NO" accordingly.

0 0

Похожие вопросы

Топ вопросов за вчера в категории Информатика

Последние заданные вопросы в категории Информатика

Задать вопрос