Urgent.News

What's breaking now, across thousands of outlets.

Tech

Проверка палиндрома на Python: разбор учебной задачи

Задача Дана строка s , состоящая из букв, цифр и пробелов. Определить, читается ли она одинаково слева направо и справа налево, без учёта регистра и пробелов . Классическая задача на строки, знакомая каждому, кто открывал учебник по программированию. Решение Идея простая: приводим строку к «чистому» виду (только буквы/цифры в нижнем регистре), а затем сравниваем её с перевёрнутой копией. Если…

The task is to determine whether a given string reads the same forwards and backwards, disregarding case and spaces. This classic string problem is familiar to anyone who has opened a programming textbook. The solution is straightforward: first, strip the string down to its "clean" form, retaining only letters and digits in lowercase. Then, compare this cleaned string with its reversed copy. If they match, we have a palindrome.

The `is_palindrome` function takes a string `s` as input. It first creates a "cleaned" version of the string by joining together only alphanumeric characters, converted to lowercase. Next, it compares this cleaned string to its reversed version. If they are identical, the function returns `True`, indicating the string is a palindrome. Otherwise, it returns `False`.

To illustrate, consider the phrases "А роза упала на лапу Азора" and "python". The first phrase is indeed a palindrome, as confirmed by the output `True`. The second, "python", is clearly not a palindrome, yielding `False` as output.

The `isalnum()` method filters out spaces and punctuation, while `[::-1]` generates a reversed copy of the string. This approach scans the characters just once, embodying the classic "brute force" method that is both easy to understand and adaptable across programming languages.

The time complexity of this algorithm is O(n), where n is the length of the string, since each character is processed a single time. Memory usage is also O(n), as a new string of the same length is created for the cleaned version.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

Receipts, not screenshots: a practical guide to verifying on-chain claims

Receipts, not screenshots: a practical guide to verifying on-chain claims If a bot tells you it did something on-chain, "trust me" is not evidence. A screenshot is not evidence either. The only thing that settles the question is a receipt : what ran, what came back, and a replay path that anyone — who was not there — can follow.

More from Tuesday 13 October →